diff options
| author | mo khan <mo@mokhan.ca> | 2025-01-22 14:42:53 -0700 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-01-22 14:42:53 -0700 |
| commit | 08fe640cc61a7c587297e079a2d174534fab5ff3 (patch) | |
| tree | e0de439070509f6a7c5dc93226efd32aff6b6da4 /assignments/3/caesar.rb | |
| parent | 8316a7cc5f2c7a3969aac4706ebb117f2582e1ca (diff) | |
Improve caesar cipher example in assignment 3
Diffstat (limited to 'assignments/3/caesar.rb')
| -rw-r--r-- | assignments/3/caesar.rb | 32 |
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)} |" |
