Skip to content

Instantly share code, notes, and snippets.

Rimantas Liubertas imcat

Block or report user

Report or block imcat

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
imcat / gist:884209
Created Mar 23, 2011
Caesar cipher
View gist:884209
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
You can’t perform that action at this time.