How to safely replace all spaces with underscores with ruby?

This works for any lines with spaces in them.

str.downcase.tr!(" ", "_") 

but lines that do not have spaces are simply deleted

So, "New School" will change to "new_school", but the "color" will be "", nothing!

+50
ruby ruby-on-rails ruby-on-rails-3
Sep 25 '11 at 17:01
source share
8 answers

Documents for tr! say

 Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made. 

I think you will get the correct results if you use tr without an exclamation.

+29
Sep 25 '11 at 17:09
source share
— -

with space

 str = "New School" str.parameterize.underscore => "new_school" 

without space

 str = "school" str.parameterize.underscore => "school" 

Edit: - we can also pass '_' as a parameter for parameterization.

with space

 str = "New School" str.parameterize('_') => "new_school" 

without space

 str = "school" str.parameterize('_') => "school" 
+62
Apr 02 '15 at 6:40
source share

If you are interested in getting a string in the case of a snake , then the proposed solution does not quite work, because you can get underscore concatenation and start / end underscores.

for example

 1.9.3-p0 :010 > str= " John Smith Beer " => " John Smith Beer " 1.9.3-p0 :011 > str.downcase.tr(" ", "_") => "__john___smith_beer_" 

This solution below will work better:

 1.9.3-p0 :010 > str= " John Smith Beer " => " John Smith Beer " 1.9.3-p0 :012 > str.squish.downcase.tr(" ","_") => "john_smith_beer" 

squish is a String method provided by Rails

+33
Jan 17 '13 at 15:15
source share

Old question, but ...

For all spaces, you probably want something more:

 "hey\t there world".gsub(/\s+/, '_') # hey_there_world 

This gets tabs and newlines, as well as spaces, and replaces one _ .

Regular expression can be changed according to your needs. For example:

 "hey\t there world".gsub(/\s/, '_') # hey__there___world 
+6
Jul 21 '15 at 23:29
source share
 str.downcase.tr(" ", "_") 

Note: No "!"

+5
Sep 25 '11 at 17:10
source share

You can also do str.gsub ("," _ ")

+1
Sep 26 '11 at 9:19 a.m.
source share
 str = "Foo Bar" str.tr(' ','').underscore => "foo_bar" 
+1
Feb 11 '15 at 0:50
source share

If you use rails 5 and above, you can achieve the same level with

 str.parameterize(separator: '_') 
0
Dec 22 '17 at 13:18
source share



All Articles