You want a mapping like this:
input: abcdefghijklmnopqrstuvwxyz
output: wxyzabcdefghijklmnopqrstuv
Unfortunately your approach doesn't work for the first 4 letters:
("a".ord - 4).chr #=> "]"
("b".ord - 4).chr #=> "^"
("c".ord - 4).chr #=> "_"
("d".ord - 4).chr #=> "`"
I'd use String#tr
. It replaces each occurrence in the first string with the corresponding character in the second string:
"m^aerx%e&gsoi!".tr("abcdefghijklmnopqrstuvwxyz", "wxyzabcdefghijklmnopqrstuv")
#=> "i^want%a&coke!"
There's also a "c1-c2 notation to denote ranges of characters":
"m^aerx%e&gsoi!".tr("a-z", "w-za-v")
#=> "i^want%a&coke!"
The documentation further says:
If
to_str
is shorter thanfrom_str
, it is padded with its last character in order to maintain the correspondence.
So it can be used to easily replace the "special characters" with a space:
"m^aerx%e&gsoi!".tr("a-z@#$%^&*", "w-za-v ")
#=> "i want a coke!"