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 |