sjsc
sjsc

Reputation: 4632

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"?

Upvotes: 18

Views: 10183

Answers (5)

ruby-in-case-on-camel-neckenter code here`#M001633

Upvotes: 0

Weston Ganger
Weston Ganger

Reputation: 6712

I think this is a simpler solution:

"SomeWordHere".titleize.downcase

Upvotes: 15

Anurag
Anurag

Reputation: 141879

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"

Upvotes: 31

Mark Byers
Mark Byers

Reputation: 838216

You can use a regular expression:

puts "SomeWordHere".gsub(/[a-zA-Z](?=[A-Z])/, '\0 ').downcase

Output:

some word here

One reason you might prefer this is if your input could contain dashes or underscores and you don't want to replace those with spaces:

puts "Foo-BarBaz".underscore.gsub('_', ' ')
puts "Foo-BarBaz".gsub(/[a-zA-Z](?=[A-Z])/, '\0 ').downcase

Output:

foo bar baz
foo-bar baz

Upvotes: 6

Jakub Hampl
Jakub Hampl

Reputation: 40543

Nope there is no built-in method that I know of. Any more efficient then a one-liner? Don't thinks so. Maybe humanize instead of the gsub, but you don't get exactly the same output.

Upvotes: 1

Related Questions