If you want to replace multiple characters, you can use gsub
to replace them as specified.
I received a comment from @scivola and corrected the article. @scivola Thank you very much for your kindness!
The following example
x = "TOKYO"
y = x.gsub(/[TOKY]/, "T" => "5", "O" => "3", "K" => "6", "Y" => "1")
puts y
=> 53613
It will replace the corresponding ones character by character. Also, since it is converted to a character string at the time of replacement, the result does not change whether you write 5 or "5".
Also, for "replacement" that replaces one character with one character, it seems simpler and faster to use the dedicated method String # tr than to use gsub!
y = x.tr("TOKY", "5361")
Recommended Posts