Last active
June 23, 2024 23:21
-
-
Save havenwood/61334e8c264c9c6d0e5b1e45d373759e to your computer and use it in GitHub Desktop.
A Caesar cipher example in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Caesar | |
def initialize(rot: 13, lower: [*'a'..'z'], upper: [*'A'..'Z']) | |
@rot = rot | |
@book = book(lower:, upper:) | |
end | |
def cipher(message) = message.gsub(/[a-zA-Z]/, @book) | |
alias_method :call, :cipher | |
private | |
def book(lower:, upper:) = dict(lower).merge(dict(upper)) | |
def dict(chars) = chars.rotate(@rot).zip(chars).to_h | |
end | |
rot13 = Caesar.new | |
p rot13.cipher('Cicada') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment