Created
March 23, 2011 22:54
-
-
Save imcat/884209 to your computer and use it in GitHub Desktop.
Caesar cipher
This file contains hidden or 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
def caesar_cipher(string, shift, decode = false) | |
alphabet = ('A'..'Z').to_a # create the range of uppercase letter and convert it to an array: ['A', 'B', … 'Z'] | |
shift = -shift if decode # if decoding, negate the shift. Negative value changes the dirrection of Array.rotate | |
key = alphabet.rotate(shift) # produce encode or decode array by rotating the alphabet. ['A', 'B', 'C', 'D'].rotate(2) => ['C', 'D', 'A', 'B'] | |
string.chars.inject("") do |result, char| # string.chars gives the enumerator of the chars in the string. Each char will be processed in the block assigned to 'char' | |
case_changed = char.upcase! # upcase will return nil if no changes were made | |
result_char = (alphabet.include?(char) ? key[alphabet.index(char)] : char) #if char is in the alphabet, get the corresponding char from key array | |
result << (case_changed ? result_char.downcase : result_char) #if original char was lowercase then lowercase the result char and append to result string | |
end | |
end | |
def caesar_decode(string, shift) | |
caesar_cipher string, shift, true #call caesar_cipher with decode flag set | |
end | |
alias caesar_encode caesar_cipher #create an alias for caesar_cipher method named caesar_encode | |
puts caesar_encode("the quick brown fox Jumps Over the lazy dog", 3) | |
puts caesar_decode("wkh txlfn eurzq ira Mxpsv Ryhu wkh odcb grj", 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment