Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 655
rugbert Avatar asked Sep 25 '11 17:09

rugbert


People also ask

How do you replace a string in Ruby?

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

How do you get rid of spaces in Ruby?

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 .

What is whitespace in Ruby?

Whitespace refers to any of the following characters: Null. Horizontal tab. Line feed. Vertical tab.


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

EDIT:

For Rails 5 and above, use str.parameterize(separator: '_')

like image 153
Sampat Badhe Avatar answered Oct 29 '22 16:10

Sampat Badhe