Home » Ruby » how to safely replace all whitespaces with underscores with ruby?

how to safely replace all whitespaces with underscores with ruby?

Posted by: admin November 30, 2017 Leave a comment

Questions:

This works for any strings that have whitespaces in them

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

but strings that dont have whitespaces just get deleted

So “New School” would change into “new_school” but “color” would be “”, nothing!

Answers:

The docs 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’ll get the correct results if you use tr without the exclamation.

Questions:
Answers:

with space

str = "New School"
str.parameterize.underscore

=> "new_school"

without space

str = "school"
str.parameterize.underscore

=> "school"

Edit :-
also we can pass ‘_’ as parameter to parameterize.

with space

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

=> "new_school"

without space

str = "school"
str.parameterize('_')

=> "school"

Questions:
Answers:

If you’re interested in getting a string in snake case, then the proposed solution doesn’t quite work, because you may get concatenated underscores and starting/trailing 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 would 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

Questions:
Answers:

Old question, but…

For all whitespace you probably want something more like this:

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

This gets tabs and new lines as well as spaces and replaces with a single _.

The regex can be modified to suit your needs. E.g:

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

Questions:
Answers:
str.downcase.tr(" ", "_")

Note: No “!”

Questions:
Answers:

You can also do
str.gsub(” “, “_”)

Questions:
Answers:
str = "Foo Bar"
str.tr(' ','').underscore

=> "foo_bar"