Class: Enigma::Rotor

Inherits:
Object
  • Object
show all
Defined in:
lib/enigma/rotor.rb

Overview

The engima rotor has two contact points and can transform a letter going forward or reverse. In addition the rotor supports rotating (offsetting) and has a turnover point that will change other rotors

Usage:

rotor = Enigma::Rotor.new(mapping: ..., turnover: ..., position: ...)
rotor.forward('A') # '.'
rotor.reverse('B') # '.'
rotor.rotate and return unless rotor.turnover?

Defined Under Namespace

Modules: Mappings, Offset, Position, Turnover

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mappings: Mappings::DEFAULT, turnover: Turnover::DEFAULT, position: Position::DEFAULT) ⇒ Rotor

Returns a new instance of Rotor.


38
39
40
41
42
43
# File 'lib/enigma/rotor.rb', line 38

def initialize(mappings: Mappings::DEFAULT, turnover: Turnover::DEFAULT, position: Position::DEFAULT)
  @mappings = mappings
  @turnover = turnover
  @position = position
  reset!
end

Class Method Details

.rotorsObject


70
71
72
73
74
75
76
# File 'lib/enigma/rotor.rb', line 70

def self.rotors
  [
    new(mappings: Mappings::A, turnover: Turnover::A),
    new(mappings: Mappings::B, turnover: Turnover::B),
    new(mappings: Mappings::C, turnover: Turnover::C),
  ]
end

Instance Method Details

#forward(letter) ⇒ Object


54
55
56
57
58
# File 'lib/enigma/rotor.rb', line 54

def forward(letter)
  return letter unless ALPHABET.include?(letter)

  @mappings[(ALPHABET.index(letter) + @position + @offset) % ALPHABET.length]
end

#reset!Object


66
67
68
# File 'lib/enigma/rotor.rb', line 66

def reset!
  @offset = Offset::DEFAULT
end

#reverse(letter) ⇒ Object


60
61
62
63
64
# File 'lib/enigma/rotor.rb', line 60

def reverse(letter)
  return letter unless ALPHABET.include?(letter)

  ALPHABET[(@mappings.index(letter) + @position - @offset) % ALPHABET.length]
end

#rotateObject


45
46
47
48
# File 'lib/enigma/rotor.rb', line 45

def rotate
  @offset = @offset.next % ALPHABET.length
  self
end

#turnover?Boolean

Returns:

  • (Boolean)

50
51
52
# File 'lib/enigma/rotor.rb', line 50

def turnover?
  ((@position + @offset) % ALPHABET.length).eql?(@turnover)
end