loading...

re: Daily Challenge #42 - Caesar Cipher VIEW POST

FULL DISCUSSION
 

Ruby

class String
  def cesar_encrypt(key)
    raise ArgumentError, 'Key must be between 1 and 26 inclusive.' if key < 1 || key > 26

    letters_min = ('a'..'z').to_a
    letters_maj = ('A'..'Z').to_a

    result = tr!(letters_min.join, letters_min.rotate(key).join)
    result.tr(letters_maj.join, letters_maj.rotate(key).join)
  end

  def cesar_decrypt(key)
    raise ArgumentError, 'Key must be between 1 and 26 inclusive.' if key < 1 || key > 26

    letters_min = ('a'..'z').to_a
    letters_maj = ('A'..'Z').to_a

    result = tr!(letters_min.join, letters_min.rotate(-key).join)
    result.tr(letters_maj.join, letters_maj.rotate(-key).join)
  end
end

pp 'efgfoe uif fbtu xbmm pg uif dbtumfabAB'.cesar_decrypt(1)
pp 'defend the east wall of the castlezaZA'.cesar_encrypt(1)
code of conduct - report abuse