Search code examples
rubyregexcase-sensitivegsubcase-insensitive

gsub method and regex (case sensitive and case insensitive)


In ruby, I want to substitute some letters in a string, is there a better way of doing this?

string = "my random string"
string.gsub(/a/, "@").gsub(/i/, "1").gsub(/o/, "0")`

And if I want to substitute both "a" and "A" with a "@", I know I can do .gsub(/a/i, "@"), but what if I want to substitute every "a" with an "e" and every "A" with an "E"? Is there a way of abstracting it instead of specifying both like .gsub(/a/, "e").gsub(/A/, "E")?


Solution

  • You can use a Hash. eg:

    h = {'a' => '@', 'b' => 'B', 'A' => 'E'}
    "aAbBcC".gsub(/[abA]/, h)
    # => "@EBBcC"