Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Converting "SomeWordHere" to "some word here"

I know you can do something like:

"SomeWordHere".underscore.gsub("_", " ") 

to get "some word here".

I thought that might be a little too much for something so simple. Is there a more efficient way (maybe a built-in method?) to convert "SomeWordHere" to "some word here"?

like image 394
sjsc Avatar asked May 16 '10 02:05

sjsc


People also ask

What is humanize in Ruby?

humanize(capitalize: true, keep_id_suffix: false) public. Capitalizes the first word, turns underscores into spaces, and (by default)strips a trailing '_id' if present. Like titleize, this is meant for creating pretty output.

How do you typecast in Ruby?

Ruby has a well defined and often used typecasting infrastructure. to_s casts a value to a String , to_f casts a value to a Float , to_i casts a value to an Integer , etc. These are a helpful tool in our toolbox, but this too has limitations. First, there is no #to_* method that casts values into true or false .


2 Answers

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"
like image 168
Anurag Avatar answered Oct 15 '22 06:10

Anurag


I think this is a simpler solution:

"SomeWordHere".titleize.downcase

like image 37
Weston Ganger Avatar answered Oct 15 '22 06:10

Weston Ganger