Ruby on Rails: Converting "Somewordhere" to "Some Word Here"

Ruby on Rails: Converting SomeWordHere to some word here

alt text

The methods underscore and humanize are designed for conversions between tables, class/package names, etc. You are better off using your own code to do the replacement to avoid surprises. See comments.

"SomeWordHere".underscore => "some_word_here"

"SomeWordHere".underscore.humanize => "Some word here"

"SomeWordHere".underscore.humanize.downcase => "some word here"

Converting camel case to underscore case in ruby

Rails' ActiveSupport
adds underscore to the String using the following:

class String
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end

Then you can do fun stuff:

"CamelCase".underscore
=> "camel_case"


Related Topics



Leave a reply



Submit