Skip to content

Instantly share code, notes, and snippets.

@tsevdos
Last active January 30, 2016 10:22
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 tsevdos/4850c716d8eff43b6377 to your computer and use it in GitHub Desktop.
Save tsevdos/4850c716d8eff43b6377 to your computer and use it in GitHub Desktop.
Atbash Cipher
class Atbash
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)
NUMBERS = %w(0 1 2 3 4 5 6 7 8 9)
PUNCTUATION = [' ', ',', '.']
def self.encode(str)
cipher = []
str.chars.each do |char|
next if PUNCTUATION.include?(char)
cipher << char if NUMBERS.include?(char)
cipher << encode_character(char).downcase if LETTERS.include?(char.upcase)
end
cipher.join('').scan(/.{5}|.+/).join(' ')
end
def self.encode_character(char)
char_index = LETTERS.index(char.upcase)
half_alphabet_size = (LETTERS.size / 2) # 13
first_half_of_alphabet = LETTERS[0...half_alphabet_size]
second_half_of_alphabet = LETTERS[half_alphabet_size...LETTERS.size]
encoded_char_index = (half_alphabet_size - 1) - char_index
if char_index >= half_alphabet_size
return first_half_of_alphabet[encoded_char_index]
else
return second_half_of_alphabet[encoded_char_index]
end
nil
end
private_class_method :encode_character
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment