-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaeser.rb
56 lines (42 loc) · 1023 Bytes
/
caeser.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
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true
# make the text downcase just to keep it simple
# letters must be changed, symbols not.
class Caeser
attr_reader :text, :rotation
def initialize(text, rotation)
@text = text.downcase
@rotation = rotation
end
def cipher
text
.chars
.map { |letter| cipher_alphabet[letter] || letter }
.join
end
def decipher
text
.chars
.map { |letter| decipher_alphabet[letter] || letter }
.join
end
def self.cipher(text, rotation)
new(text, rotation).cipher
end
def self.decipher(text, rotation)
new(text, rotation).decipher
end
private
def cipher_alphabet
return @cipher_alphabet unless @cipher_alphabet.nil?
@cipher_alphabet = {}
('a'..'z').each_with_index do |v, i|
index = i + rotation
index -= 26 if index > 25
@cipher_alphabet[v] = ('a'..'z').to_a[index]
end
@cipher_alphabet
end
def decipher_alphabet
@decipher_alphabet ||= cipher_alphabet.invert
end
end