Tutorial :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.


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


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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »