Class: Ciphers::Autokey

Inherits:
Object
  • Object
show all
Defined in:
lib/ciphers/autokey.rb

Instance Method Summary collapse

Constructor Details

#initialize(alphabet: Ciphers::LATIN, key:) ⇒ Autokey

Returns a new instance of Autokey.



3
4
5
6
7
# File 'lib/ciphers/autokey.rb', line 3

def initialize(alphabet: Ciphers::LATIN, key: )
    alphabet = alphabet.chars if alphabet.is_a? String
  @alphabet = alphabet.to_a.freeze
    @key = key.upcase.freeze
end

Instance Method Details

#decrypt(string) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/ciphers/autokey.rb', line 19

def decrypt(string)
  string.each_char.with_index.with_object('') do |(char, i), ret|
    ret << char and next unless alphabet.include?(char)
    key_char = "#{key}#{ret}"[i]
    row = table.fetch key_char
    col = row.index(char)
    ret << alphabet[col]
  end
end

#encrypt(string) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/ciphers/autokey.rb', line 9

def encrypt(string)
    string.each_char.with_index.with_object('') do |(char, i), ret|
      ret << char and next unless alphabet.include?(char)
      key_char = "#{key}#{string}"[i]
    row = table.fetch key_char
    col = alphabet.index(char)
    ret << row[col]
  end
end