forked from CoderAcademy-BRI/ruby-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path37_caesar_cipher.rb
More file actions
44 lines (40 loc) · 1.23 KB
/
Copy path37_caesar_cipher.rb
File metadata and controls
44 lines (40 loc) · 1.23 KB
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
# Write a class that implements the Caesar cipher.
# (http://practicalcryptography.com/ciphers/caesar-cipher/)
#
# When given a string, will return an uppercase string with each letter shifted
# forward in the alphabet by however many spots the cipher was initialized to.
#
# For example:
#
# c = CaesarCipher.new(5); # creates a CipherHelper with a shift of five
# c.decode('BFKKQJX') # returns 'WAFFLES'
#
# If the shift pushes beyond the end of the alphabet, start back at 'A'
# Example:
# c = CaesarCipher.new(1)
# c.encode('ZOO') # returns 'APP'
#
# If something in the string is not in the alphabet (e.g. punctuation, spaces), simply leave it as is.
#
# The shift will always be in range of [1, 26].
ALPHABET = ("A".."Z").to_a
# it would be more performant to use a hash-based solution
class CaesarCipher
def initialize(shift)
@shift = shift
end
def encode(string)
encoded_string = ""
for letter in string.upcase.chars
encoded_string << ALPHABET[(ALPHABET.index(letter) + @shift) % 26]
end
return encoded_string
end
def decode(string)
decoded_string = ""
for letter in string.upcase.chars
decoded_string << ALPHABET[(ALPHABET.index(letter) - @shift) % 26]
end
return decoded_string
end
end