Created
November 22, 2011 03:30
-
-
Save EricR/1384809 to your computer and use it in GitHub Desktop.
Caesar Cypher in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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