Skip to content

Instantly share code, notes, and snippets.

@EricR
Created November 22, 2011 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EricR/1384809 to your computer and use it in GitHub Desktop.
Save EricR/1384809 to your computer and use it in GitHub Desktop.
Caesar Cypher in Ruby
class Caesar
def self.encrypt(shift, message)
apply_algorithm(:encrypt, shift, message)
end
def self.decrypt(shift, message)
apply_algorithm(:decrypt, shift, message)
end
private
def self.apply_algorithm(direction, shift, message)
letters = %w{A B C D E F G H I J K L M N O P Q R S T U V W X Y Z}
message.upcase.split(//).map do |letter|
if letters.include?(letter)
shift = direction == :encrypt ? shift : -shift
letters.rotate(shift)[letters.index(letter)]
else
letter
end
end.join
end
end
# puts Caesar.encrypt(72,"Hello World! This is an encypted message.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment