how to safely replace all whitespaces with underscores with ruby?
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!
Solution 1:
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"
EDIT:
For Rails 5 and above, use str.parameterize(separator: '_')
Solution 2:
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.