ROT13. ROT13 is a popular cipher. With it, we rotate characters in text forward, or backward, 13 places. This is an easily reversible cipher. In the Ruby language, we can implement ROT13 with the tr method.
Example. First, we introduce the tr string method. This method receives two arguments: a string containing characters that are to be replaced, and a second string of the replacement characters.
Tip The exclamation mark after tr means that tr will change the string in-place. We need to assign no variables.
Note In the following examples, we refine our rot13 code, using a method and an abbreviated syntax for tr.
Def. Here we refine our approach and place the tr call inside a method. We use the def keyword to designate a method. In rot13(), we return the result of a tr call. When we call rot13 on the result of rot13, we get the original string back.
Tip In Ruby, a return keyword is not always needed. A single-statement method will automatically treat the statement as a return value.
Ruby program that uses tr
# Input string.
value = "gandalf"# Use tr to translate one alphabet to another.
# Our result.
Ranges. The tr method can receive character ranges, like a regular expression. So the code "a-z" means the entire lowercase alphabet. We use this to rewrite the rot13 method. This version is shorter to type.
And This method will have fewer possible typos. It is easier to review for correctness.
Ruby program that uses def, rot13 method
# Use rot13 method.
Summary. ROT13 is not encryption. It 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.
Ruby program that uses character ranges, tr
return value.tr("a-z", "n-za-m")