NullVoxPopuli
NullVoxPopuli

Reputation: 65133

Ruby on Rails: I want to remove non letters to create a username

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.

Upvotes: 3

Views: 886

Answers (2)

murphyslaw
murphyslaw

Reputation: 636

'Master Yoda'.underscore # => 'master yoda'
'MasterYoda'.underscore # => 'master_yoda'
'Master Yoda'gsub(' ', '') # => 'MasterYoda'
'Master Yoda'.gsub(' ', '').downcase # => 'masteryoda'

Upvotes: 1

TJ Koblentz
TJ Koblentz

Reputation: 6948

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

Upvotes: 0

Related Questions