ruby-on-railsrubyruby-on-rails-3

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

  • 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.