How to implement the ROT13 algorithm (replace a letter with the 13th letter after it) in Ruby

1 Answer

0 votes
# ROT13 is a simple substitution cipher that replaces a letter with the 13th letter 
# after it in the alphabet. Because the English alphabet has 26 letters (13 * 2), 
# applying ROT13 twice restores the original text (it is its own inverse).

# Applies the ROT13 cipher to a string.
#
# ROT13 rotates each letter by 13 positions in the alphabet.
# Non-alphabetic characters are left unchanged.
# Applying ROT13 twice returns the original text.
#
# @param text [String] The text to encode or decode.
# @return [String] The ROT13-transformed string.
def rot13(text)
  text.tr(
    'A-Za-z',
    'N-ZA-Mn-za-m'
  )
end

# Input text
input = "Hello, World! 123"

# Encode the input
encoded = rot13(input)

# Decode by applying ROT13 again
decoded = rot13(encoded)

# Display results
puts "Input   : #{input}"
puts "Encoded : #{encoded}"
puts "Decoded : #{decoded}"


# run:
#
# Input   : Hello, World! 123
# Encoded : Uryyb, Jbeyq! 123
# Decoded : Hello, World! 123
#

 



answered 2 days ago by avibootz

Related questions

...