how to safely replace all whitespaces with underscores with ruby?

Pass ‘_’ as parameter to parameterize(separator: ‘-‘). For Rails 4 and below, use str.parameterize('_')

Examples:

with space

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

=> "new_school"

without space

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

=> "school"

You can also solve this by chaining underscore to parameterize.

Examples:

with space

str = "New School"
str.parameterize.underscore

=> "new_school"

without space

str = "school"
str.parameterize.underscore

=> "school"

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)