-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshift_cipher.rb
46 lines (42 loc) · 1.32 KB
/
shift_cipher.rb
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
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env ruby
# frozen_string_literal: true
# Lines 15,16,20,21,33,34,38,39 were added by me to fix a bug. The rest of the code is from
# Ruby: Classes and Modules on LinkedIn learning
class ShiftCipher
@@upcase = [*'A'..'Z']
@@downcase = [*'a'..'z']
def self.encode(string, pos = 3)
string.chars.map do |char|
if @@downcase.include?(char)
i = @@downcase.find_index(char)
total = i + pos
mod = total < @@downcase.length ? total : total % @@downcase.length
@@downcase[mod]
elsif @@upcase.include?(char)
i = @@upcase.find_index(char)
total = i + pos
mod = total < @@downcase.length ? total : total % @@downcase.length
@@upcase[mod]
else
char
end
end.join('')
end
def self.decode(string, pos = 3)
string.chars.map do |char|
if @@downcase.include?(char)
i = @@downcase.find_index(char)
total = i - pos
mod = total < @@downcase.length ? total : total % @@downcase.length
@@downcase[mod]
elsif @@upcase.include?(char)
i = @@upcase.find_index(char)
total = i - pos
mod = total < @@downcase.length ? total : total % @@downcase.length
@@upcase[mod]
else
char
end
end.join('')
end
end