-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex7.rb
More file actions
33 lines (30 loc) · 747 Bytes
/
ex7.rb
File metadata and controls
33 lines (30 loc) · 747 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class CeasarCipher
def initialize(shift)
if (1..26).include?(shift)
@shift = shift
else
raise "SHIFT OUT OF BOUNDS"
end
end
def encode(string)
process_string(string, @shift)
end
def decode(string)
process_string(string, -@shift)
end
def process_string(string, shift)
encoded_str = string.chars.map do |letter|
if letter.match?(/[A-Za-z]/)
base = letter.match?(/[A-Z]/) ? 'A' : 'a'
(((letter.ord - base.ord + shift) % 26) + base.ord).chr.upcase
else
letter
end
end
encoded_str = encoded_str.join("")
puts encoded_str
end
end
c = CeasarCipher.new(5)
c.encode('Codewars') # returns 'HTIJBFWX'
c.decode('BFKKQJX') # returns 'WAFFLES'