Ruby ROT13 MethodDevelop a ROT13 method. ROT13 is a cipher that obscures the text content of strings.
dot net perls
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. value.tr!("abcdefghijklmnopqrstuvwxyz", "nopqrstuvwxyzabcdefghijklm") # Our result. puts value
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
def rot13(value) return value.tr("abcdefghijklmnopqrstuvwxyz", "nopqrstuvwxyzabcdefghijklm") end # Use rot13 method. puts rot13("gandalf") puts rot13(rot13("gandalf"))
tnaqnys gandalf
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
def rot13(value) return value.tr("a-z", "n-za-m") end
© 2007-2021 sam allen. see site info on the changelog