class ShiftCiphers::Caesar

Constants

DEFAULT_OFFSET

Attributes

alphabet[RW]
nonalphabet_char_strategy[RW]
offset[RW]

Public Class Methods

new(offset: DEFAULT_OFFSET, alphabet: Alphabets::DEFAULT, nonalphabet_char_strategy: :error) click to toggle source
# File lib/shift_ciphers/caesar.rb, line 6
def initialize(offset: DEFAULT_OFFSET, alphabet: Alphabets::DEFAULT, nonalphabet_char_strategy: :error)
  @offset = offset
  @alphabet = alphabet
  @nonalphabet_char_strategy = nonalphabet_char_strategy
end

Protected Class Methods

decrypt(ciphertext, **options) click to toggle source
# File lib/shift_ciphers/caesar.rb, line 43
def decrypt(ciphertext, **options)
  self.new(**options).decrypt(ciphertext)
end
encrypt(plaintext, **options) click to toggle source
# File lib/shift_ciphers/caesar.rb, line 39
def encrypt(plaintext, **options)
  self.new(**options).encrypt(plaintext)
end

Public Instance Methods

decrypt(ciphertext) click to toggle source
# File lib/shift_ciphers/caesar.rb, line 16
def decrypt(ciphertext)
  process(ciphertext, false)
end
encrypt(plaintext) click to toggle source
# File lib/shift_ciphers/caesar.rb, line 12
def encrypt(plaintext)
  process(plaintext, true)
end

Protected Instance Methods

process(text, encrypting = true) click to toggle source
# File lib/shift_ciphers/caesar.rb, line 22
def process(text, encrypting = true)
  text.each_char.reduce("") do |result, char|
    char_idx = alphabet.index(char)
    if !char_idx.nil?
      rel_offset = offset * (encrypting ? 1 : -1)
      result << alphabet[(char_idx + rel_offset) % alphabet.size]
    else
      if nonalphabet_char_strategy == :dont_encrypt
        result << char
      else
        raise CipherError.new("Character #{char.inspect} is not in the alphabet: #{alphabet.inspect}")
      end
    end
  end
end