Skip to content

Instantly share code, notes, and snippets.

@esquinas
Created October 3, 2016 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esquinas/ba093c2379b67ddeb2ad5f022ff6f0f4 to your computer and use it in GitHub Desktop.
Save esquinas/ba093c2379b67ddeb2ad5f022ff6f0f4 to your computer and use it in GitHub Desktop.
My Ruby implementation of a simple Caesar cipher
# Caesar cipher module
#
# USAGE:
# =====
# ```ruby
# my_var = Plaintext.new 'TOO MANY SECRETS'
# my_var.rotn # => "GBB ZNAL FRPERGF"
# my_var # => "TOO MANY SECRETS"
# ```
# There is a bang method to make changes permanent:
# ```ruby
# my_var = Plaintext.new 'TOO MANY SECRETS'
# my_var.rotn! # => "GBB ZNAL FRPERGF"
# my_var # => "GBB ZNAL FRPERGF"
# ```
#
# Parameters:
# -----------
# 1. **amount**: The number of positions to jump inside the alphabet.<br>
# (defaults to `13`)
# ```ruby
# Plaintext.new('Caesar').rotn # => "Pnrfne"
# Plaintext.new('Caesar').rotn(3) # => "Fdhvdu"
# Plaintext.new('Caesar').rotn(0) # => "Caesar"
# Plaintext.new('Caesar').rotn(-3) # => "Zxbpxo"
# ```
#
# #### INFO:
# - https://en.wikipedia.org/wiki/Caesar_cipher
# - https://es.wikipedia.org/wiki/ROT13
#
module CaesarCipher
def rotn!(amount = 13)
lut_hash = [*('a'..'z')].zip([*('a'..'z')].rotate(amount)).to_h
lut_hash.merge! [*('A'..'Z')].zip([*('A'..'Z')].rotate(amount)).to_h
lut_hash.merge! [*('0'..'9')].zip([*('0'..'9')].rotate(amount)).to_h
hash_sub! lut_hash
end
def rotn(*args)
dup.rotn!(*args)
end
private
def hash_sub!(hash)
chars.each_with_index do |char, i|
self[i] = hash.fetch char, char
end
self
end
end
class Plaintext < String
include CaesarCipher
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment