how to safely replace all whitespaces with underscores with ruby?

This works for any strings that have whitespaces in them!(" ", "_")

but strings that dont have whitespaces just get deleted

So "New School" would change into "new_school" but "color" would be "", nothing!


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