0 Replies - 1284 Views - Last Post: 12 November 2009 - 11:30 AM

#1 EdwinNameless   User is offline

  • D.I.C Addict
  • member icon

Reputation: 128
  • View blog
  • Posts: 723
  • Joined: 15-October 09

ROT13

Posted 12 November 2009 - 11:30 AM

Description: Call the "rot13" function, passing in the lowercase piece of text to encrypt.ROT13 is a cipher that replaces a character by a character located 13 letters further in the alphabet. The interesting property of ROT13 is that applying ROT13 again to a ciphered text gives the original text. Only works for lowercase letters!
def rot13 text
  return text.each_byte.inject("") do
    |str,n| 
    # Checking we have a lowercase letter.
    # We don't want to "downcase" as rot13(rot13) would alter 
    # the original message
    if n >= 97 and n <= 122
      # 97 is used as the offset, as this is the position of the letter 'a'
      # in the ASCII table, see: puts "a"[0]
      # Add 13 modulo 26 to return at the beginning of the alphabet.
      str.concat((((n+13)-97)%26)+97)
    else 
      str.concat(n) # else return "as is".
  end
end
# Apply ROT13 to a piece of text.
puts rot13(<<TEXT)
this is some text to convert
TEXT

# And verify that applying it again gives the original message!
puts rot13(rot13(<<TEXT)
this is some text to convert
TEXT
)


Is This A Good Question/Topic? 0
  • +

Page 1 of 1