With ROT13, we rotate characters in text forward, or backward, 13 places. This is an easily-reversible cipher and it can be implemented in Ruby.
In the Ruby language, we can implement ROT13 with the tr method. We can even use range syntax in the tr method to reduce the amount of possible errors.
We use the tr string
method. In the following examples, we refine our rot13
code, using a method and an abbreviated syntax for tr.
string
containing characters that are to be replaced.string
with the replacement characters.string
in-place. We need to assign no variables.# Input string. value = "gandalf" # Use tr to translate one alphabet to another. value.tr!("abcdefghijklmnopqrstuvwxyz", "nopqrstuvwxyzabcdefghijklm") # Our result. puts valuetnaqnys
Here we refine our approach and place the tr call inside a method. We use the def
keyword to designate a method. When we call rot13
on the result of rot13
, we get the original string
back.
def rot13(value) # Use expanded syntax in tr. return value.tr("abcdefghijklmnopqrstuvwxyz", "nopqrstuvwxyzabcdefghijklm") end def rot13range(value) # Use range syntax with tr. return value.tr("a-z", "n-za-m") end # Use rot13 methods. puts rot13("gandalf") puts rot13(rot13("gandalf")) puts rot13range("gandalf") puts rot13range(rot13range("gandalf"))tnaqnys gandalf tnaqnys gandalf
ROT13 is easy to reverse. It is helpful to implement ROT13 in computer languages to learn how to manipulate strings. Often, languages contain helpful translate methods like tr.