This repository was archived by the owner on Feb 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaesar_cipher.rb
More file actions
54 lines (37 loc) · 1.53 KB
/
Copy pathcaesar_cipher.rb
File metadata and controls
54 lines (37 loc) · 1.53 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
45
46
47
48
49
50
51
52
53
54
def shift_letter(letter, offset)
ascii_code = {
'A' => 65,
'a' => 97,
'Z' => 90,
'z' => 122
}
return letter unless letter.match(/[A-Za-z]/)
return (letter.ord + offset).chr if (letter.ord + offset).chr.match(/[A-Za-z]/)
if offset.positive?
if letter.ord + offset > ascii_code['Z'] && letter.ord + offset < ascii_code['a']
return (ascii_code['A'] + (letter.ord + offset - 1 - ascii_code['Z'])).chr
end
(ascii_code['a'] + (offset - 1)).chr if (letter.ord + offset) > ascii_code['z']
elsif offset.negative?
if letter.ord + offset < ascii_code['a'] && letter.ord + offset > ascii_code['Z']
return (ascii_code['z'] + (letter.ord + offset + 1 - ascii_code['a'])).chr
end
(ascii_code['Z'] + (offset + 1)).chr if (letter.ord + offset) < ascii_code['A']
end
end
def encrypt_message_with_caesar_cipher(message, offset)
message.split('').map { |letter| shift_letter(letter, offset) }.join
end
print 'Type a message to be encrypted: '
user_message = gets
print "\n"
print 'Choose the size of the shift (positive values represent a shift to the right, while negative value represent a shift to the left): '
until (offset = gets).match(/-?[0-9]/)
print "\n"
puts 'The input should be a number!'
print "\n"
print 'Choose the size of the shift (positive values represent a shift to the right, while negative value represent a shift to the left): '
end
print "\n"
print 'Your message encrypted with the Cesar cipher is: '
puts encrypt_message_with_caesar_cipher(user_message, offset.to_i)