Skip to content

Instantly share code, notes, and snippets.

@tsevdos
Last active Jan 30, 2016
Embed
What would you like to do?
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