views:

41

answers:

2

Let's say I have the name "Master Yoda"

How would I auto convert it to be lowercase, and replace spaces with underscores... or just get rid of the spaces.

so maybe turn it into master_yoda or masteryoda

I'm looking for the most concise solution possible.

+2  A: 

The method to do this is underscore from Rails' ActiveSupport::CoreExtensions::String::Inflections module.

As an added note, if any native Rails method doesn't do exactly what you want, make sure to click the "Show source" links at api.rubyonrails.org. In this case, showing the source of Inflections.underscore tells us it is actually just calling Inflector.underscore on the caller string object.

Searching for that documentation, we can find the method that really does the work (so to speak) here: http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#M000710

I know you want the most succinct answer, but just know that it is relatively simple (and also beneficial to learn) how things work "under the hood."

tjko
Sorry but that's not right. `"Blah Blah".underscore # => "blah blah"`, `"BLah Blah".underscore # => "b_lah blah"`... the `underscore` method is used for modules and such: `"ActiveRecord::Base".underscore # => "active_record/base"`
thenduks
I don't see why I was down voted for my answer... @thenduks, you proposed `underscorize` which doesn't exist. On the other hand, this does what the OP wants and even if it doesn't perfectly, I provide an explanation as to how to modify the code to find something that fits their needs.
tjko
Hmm, I must have a plugin that added underscorize and then misread the docs. So you are right, although `underscore` still isn't intended to be used for this, your suggestion of simply reading the code and writing your own version (perhaps called `underscorize`? :)) makes sense. I deleted my answer and edited the underscorize part out of yours so I could retract my downvote.
thenduks
Thanks for acknowledging this, you are right however that `Inflector.underscore` does seem to be primarily for usage on string module names, hence the `gsub.(/::/,'/')`. Then again, checking the very readable source should allow the OP to simply find an answer. In any case, I still think this solution is the most succinct, native Rails way of doing this.
tjko
A: 
'Master Yoda'.underscore # => 'master_yoda'
'Master Yoda'gsub(' ', '') # => 'MasterYoda'
'Master Yoda'.gsub(' ', '').downcaes # => 'masteryoda'
murphyslaw