Avatar


ROT13 cypher decoder in Ruby

Written by:

adelina

in RUBY

A simple method written in Ruby that takes an array of strings and decodes its elements using ROT13 cypher system.

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:

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.