Home
Ruby
ROT13 Method
This page was last reviewed on Nov 17, 2023.
Dot Net Perls
ROT13. 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.
Example. We use the tr string method. In the following examples, we refine our rot13 code, using a method and an abbreviated syntax for tr.
Argument 1 The first argument to tr is a string containing characters that are to be replaced.
Argument 2 The second argument to tr is a string with the replacement characters.
Tip The exclamation mark after tr means that tr will change the 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 value
tnaqnys
Def. 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.
Method
Tip In Ruby, a return keyword is not always needed. A single-statement method will automatically treat the statement as a return value.
Tip 2 The tr method can receive character ranges, like a regular expression. So the code "a-z" means the entire lowercase alphabet.
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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.