summaryrefslogtreecommitdiff
path: root/assignments/3/caesar.rb
diff options
context:
space:
mode:
Diffstat (limited to 'assignments/3/caesar.rb')
-rw-r--r--assignments/3/caesar.rb32
1 files changed, 24 insertions, 8 deletions
diff --git a/assignments/3/caesar.rb b/assignments/3/caesar.rb
index bc70f75..c7111e4 100644
--- a/assignments/3/caesar.rb
+++ b/assignments/3/caesar.rb
@@ -1,10 +1,26 @@
#!/usr/bin/env ruby
-key = 5
-alphabet = ('A'..'Z').to_a
-cipher = alphabet.rotate(key)
-map = Hash[cipher.zip(alphabet)]
-map[' '] = ' '
-
-ciphertext = "RTAJ TZY FY IFBS"
-puts ciphertext.chars.map { |x| map[x] }.join
+PLAIN_ALPHABET = ('A'..'Z').to_a
+
+def cipher_alphabet_for(key)
+ PLAIN_ALPHABET.rotate(key)
+end
+
+def decode(ciphertext, key)
+ mapping = Hash[cipher_alphabet_for(key).zip(PLAIN_ALPHABET)]
+ ciphertext.chars.map { |x| mapping[x] || ' ' }.join
+end
+
+key = ENV.fetch("KEY", 5).to_i
+ciphertext = ENV.fetch("CIPHERTEXT", "RTAJ TZY FY IFBS")
+
+width = (PLAIN_ALPHABET.size*2)-1
+puts "# Caesar Cipher"
+puts ""
+puts "| --------------- | --------------------------------------------------- |"
+puts "| Plain Alphabet | #{PLAIN_ALPHABET.join(",").ljust(width)} |"
+puts "| Cipher Alphabet | #{cipher_alphabet_for(key).join(",").ljust(width)} |"
+puts "| --------------- | --------------------------------------------------- |"
+puts "| Key | #{key.to_s.ljust(width)} |"
+puts "| Ciphertext | #{ciphertext.to_s.ljust(width)} |"
+puts "| Plaintext | #{decode(ciphertext, key).to_s.ljust(width)} |"