Class: Cipher::BiGrammatic

Inherits:
Substitution show all
Defined in:
lib/cipher/bigrammatic.rb

Overview

BiGrammatic

Generic bigrammatic cipherclass

Direct Known Subclasses

Playfair, Polybius

Instance Attribute Summary

Attributes inherited from Substitution

#key

Instance Method Summary (collapse)

Methods inherited from Substitution

#encode

Methods inherited from SimpleCipher

#encode

Constructor Details

- (BiGrammatic) initialize(cipher, key, type)

initialize



25
26
27
28
# File 'lib/cipher/bigrammatic.rb', line 25

def initialize(cipher, key, type)
  @key = cipher.send(:new, key, type)
  @type = type
end

Instance Method Details

- (Object) check_input(str)

check_input



46
47
48
49
50
51
52
53
# File 'lib/cipher/bigrammatic.rb', line 46

def check_input(str)
  case @type
    when Key::Playfair::WITH_J
      raise ArgumentError if str.include? ?Q
    when Key::Playfair::WITH_Q
      raise ArgumentError if str.include? ?J
  end
end

- (Object) decode(cipher_text)

decode

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cipher/bigrammatic.rb', line 32

def decode(cipher_text)
  raise ArgumentError, 'Mangled cryptogram' if cipher_text.length.odd?

  check_input(cipher_text) if @type == Key::Playfair::WITH_Q or
      @type == Key::Playfair::WITH_J

  plain_text = cipher_text.scan(/../).inject('') do |text, ct|
    text + @key.decode(ct)
  end
  return plain_text
end