I have just started learning Ruby for personal interest following the Hackerrank section available for practice. If you want you can visit the page here and start solving challenges.
This small article describes one of the challenges I have solved about a ROT13 cypher decoder. Basically, ROT13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it, in the alphabet. [more info]
Follows my solution to the challenge on Hackerrank Ruby practice.
def rot13(secret_messages)
secret_messages.map do |string|
string.tr("A-Za-z", "N-ZA-Mn-za-m")
end
end
Let’s explain briefly the code:
first of all, for any of you that have never seen Ruby before, the def keyword defines a method, called rot13 in this case;
the method takes as argument secret_messages, which is the array of strings to decode;
the map() function is an Array class method which returns a new array containing the values returned by the block;
the map-do block, which is string.tr("A-Za-z", "N-ZA-Mn-za-m")
, uses the Ruby method tr of the class String, which in general can be seen as tr(from_str, to_str) → new_str
:
In this specific case, we have from_str = “A-Za-z” and to_str = “N-ZA-Mn-za-m”.
The first specified set, [A-Za-z]
is a shorthand way of typing [ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]
.
The second is [N-ZA-Mn-za-m]
, which stays for [NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm]
.
Since the ROT13 transformation can be done using a lookup table, as explained here, what this implementation is applying is exactly a similar concept.
What tr does is reading each character from the variable string, and if it appears in the first set, it replaces it with the character in the same position in the second set.