RosettaCodeData/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-1.rb

24 lines
516 B
Ruby
Raw Permalink Normal View History

2014-01-17 05:32:22 +00:00
module VigenereCipher
2013-04-11 01:07:29 -07:00
BASE = 'A'.ord
SIZE = 'Z'.ord - BASE + 1
2014-01-17 05:32:22 +00:00
def encrypt(text, key)
crypt(text, key, :+)
2013-04-11 01:07:29 -07:00
end
2014-01-17 05:32:22 +00:00
def decrypt(text, key)
crypt(text, key, :-)
2013-04-11 01:07:29 -07:00
end
2014-01-17 05:32:22 +00:00
def crypt(text, key, dir)
text = text.upcase.gsub(/[^A-Z]/, '')
key_iterator = key.upcase.gsub(/[^A-Z]/, '').chars.map{|c| c.ord - BASE}.cycle
text.each_char.inject('') do |ciphertext, char|
offset = key_iterator.next
ciphertext << ((char.ord - BASE).send(dir, offset) % SIZE + BASE).chr
2013-04-11 01:07:29 -07:00
end
end
end