Class: Encrubto::Caesar::Encryptor

Inherits:
Object
  • Object
show all
Defined in:
lib/encrubto/caesar/encryptor.rb

Constant Summary collapse

ORIGINAL =
'abcdefghijklmnopqrstuvwxyz'

Instance Method Summary collapse

Instance Method Details

#decrypt(encrypted, offset) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/encrubto/caesar/encryptor.rb', line 19

def decrypt(encrypted, offset)
  if encrypted.is_a?(String) && offset.is_a?(Integer)
    if 0 <= offset && offset <= 26
      caesar = shift(offset)
      encrypted.tr("#{ caesar }#{ caesar.to_s.upcase }", "#{ ORIGINAL }#{ ORIGINAL.upcase }")
    else
      raise 'Offset must be between 0 and 26!'
    end
  else
      raise 'First param must be String, second param must be Integer!'
  end
end

#encrypt(str, offset) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/encrubto/caesar/encryptor.rb', line 6

def encrypt(str, offset)
  if str.is_a?(String) && offset.is_a?(Integer)
    if 0 <= offset && offset <= 26
      caesar = shift(offset)
      str.tr("#{ ORIGINAL }#{ ORIGINAL.upcase }", "#{ caesar }#{ caesar.to_s.upcase }")
    else
      raise 'Offset must be between 0 and 26!'
    end
  else
    raise 'First param must be String, second param must be Integer!'
  end
end

#shift(offset) ⇒ Object



32
33
34
35
36
# File 'lib/encrubto/caesar/encryptor.rb', line 32

def shift(offset)
  caesar_first_part = ORIGINAL[offset..ORIGINAL.length-1]
  caesar_second_part = ORIGINAL[0..offset-1]
  caesar_first_part.to_s + caesar_second_part.to_s
end