Skip to content

Instantly share code, notes, and snippets.

@elreimundo
Last active August 29, 2015 13:56
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 elreimundo/9177109 to your computer and use it in GitHub Desktop.
Save elreimundo/9177109 to your computer and use it in GitHub Desktop.
A solution to a Caesar cipher challenge in which only letters are offset and in which spaces are a handful of special characters; the original challenge featured only lowercase letters and an offset of four, but this is intended to scale easily.
def north_korean_cipher message, offset = 4
unexaggerate message.chars.map{|char| decode char, offset}.join('')
end
def unexaggerate message
message.gsub(/\d+/) { |num| num.to_i / 100 }
end
def decode char, offset
case
when lowercase?(char) then shift_by offset, char, 'a'
when uppercase?(char) then shift_by offset, char, 'A'
when space?(char) then ' '
else char
end
end
def shift_by offset, char, base_char, alphabet_length = 26
((char.ord - base_char.ord - offset) % alphabet_length + base_char.ord).chr
end
def lowercase? char
'a' <= char && 'z' >= char
end
def uppercase? char
lowercase? char.downcase
end
def space? char
'@#$%^&*'.include? char
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment