Class: CaesarCipher::Caesar

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(shift = 4) ⇒ Caesar

Returns a new instance of Caesar.



8
9
10
11
# File 'lib/caesar_cipher.rb', line 8

def initialize(shift=4)
    @shift = shift
    @alphabet = %w{a b c d e f g h i j k l m n o p q r s t u v w x y z}
end

Instance Attribute Details

#shiftObject (readonly)

Returns the value of attribute shift.



6
7
8
# File 'lib/caesar_cipher.rb', line 6

def shift
  @shift
end

Instance Method Details

#caesar_algorithm(method, text, shift) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/caesar_cipher.rb', line 30

def caesar_algorithm(method, text, shift)
    shift = method == :cipher ? shift : -shift
    text.split("").map do |c|
        if @alphabet.include? c.downcase
            pos = @alphabet.index(c.downcase)                    
            correct_case c, @alphabet.rotate(shift)[pos]
        else
            c
        end
    end.join
end

#cipher(text, shift = @shift) ⇒ Object



13
14
15
# File 'lib/caesar_cipher.rb', line 13

def cipher(text, shift=@shift)
    caesar_algorithm :cipher, text, shift
end

#correct_case(old_char, new_char) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/caesar_cipher.rb', line 22

def correct_case(old_char, new_char)
    if old_char.downcase == old_char
        new_char.downcase 
    else
        new_char.upcase
    end
end

#decipher(text, shift = @shift) ⇒ Object



17
18
19
# File 'lib/caesar_cipher.rb', line 17

def decipher(text, shift=@shift)
    caesar_algorithm :decipher, text, shift
end