views:

144

answers:

3

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

+1  A: 

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.

Jakub Hampl
Just because it's a "one liner" doesn't mean it's efficient (assuming he means runtime performance). Look at the source code for it: http://stackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby
Mark Byers
Exactly I think efficient could be interpreted in case of runtime or DRYness. I interpreted it to mean briefness but you are right about the runtime.
Jakub Hampl
+3  A: 

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
Mark Byers
Though then the output is still in titlecase.
Jakub Hampl
You can use `String#downcase` to make it all lowercase.
Zach Langley
Though the question is whether it's still more efficient ;)
Jakub Hampl
+3  A: 

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"
Anurag
Look at the implementation of underscore and humanize: http://stackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby http://snippets.dzone.com/posts/show/6350 - there's a lot of string operations in there and this is arguably more complex than the OP's original suggestion.
Mark Byers
Sorry better link - humanize for strings: http://rails.rubyonrails.org/classes/Inflector.html#M001633
Mark Byers
`underscore` and `humanize` are not only over-blown but also incorrect for OP's purposes. For example, `"UserId".underscore.humanize` gives `"User"`. `underscore`has its own replacements. For example, `"ABC::UserId".underscore` gives `"abc/user_id"`. You're right, a custom implementation is the way to go.
Anurag
DJTripleThreat