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!
First, you don't declare the type in Ruby, so you don't need the first string . To replace a word in string, you do: sentence. gsub(/match/, "replacement") .
If you want to remove only leading and trailing whitespace (like PHP's trim) you can use . strip , but if you want to remove all whitespace, you can use . gsub(/\s+/, "") instead .
Whitespace refers to any of the following characters: Null. Horizontal tab. Line feed. Vertical tab.
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: '_')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With