Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Caesar Cipher Implementation in Ruby
# CaesarCipher
# Example:
# cipher = CaesarCipher.new "Ruby is a dynamic, open source programming language!"
# cipher.encrypt(13)
# => "ehol vf n qlanzvp, bcra fbhepr cebtenzzvat ynathntr!"
class CaesarCipher
attr_accessor :sentence
def initialize(sentence)
@sentence = sentence
end
def decrypt(i)
compute { |index| index - i }
end
def encrypt(i)
compute { |index| index + i }
end
private
def compute
@sentence.downcase.each_char.each_with_object(String.new) do |char, str|
if alphabet.has_key?(char)
str << alphabet.key(yield(alphabet.fetch(char)) % 26)
else
str << char
end
end
end
def alphabet
@alphabet ||= ("a".."z").each_with_index.to_h
end
end
require 'minitest/spec'
require 'minitest/autorun'
$LOAD_PATH.unshift File.expand_path('.', File.dirname(__FILE__))
require 'caesar_cipher.rb'
describe CaesarCipher do
subject { CaesarCipher.new "Hello World!" }
it { subject.must_be_instance_of CaesarCipher }
it { subject.sentence.must_equal "Hello World!" }
describe "#encrypt" do
subject { CaesarCipher.new "Hello World!" }
it { subject.encrypt(1).must_equal "ifmmp xpsme!" }
it { subject.encrypt(13).must_equal "uryyb jbeyq!" }
end
describe "#decrypt" do
subject { CaesarCipher.new "uryyb jbeyq!" }
it { subject.decrypt(13).must_equal "hello world!" }
end
end
$LOAD_PATH.unshift File.expand_path('.', File.dirname(__FILE__))
require 'caesar_cipher.rb'
WORDS = ["what", "how", "why", "when", "where", "which", "is", "the", "of", "by", "on"]
question = "jung vf gur orfg jro senzrjbex?"
response = "Qtax Nm Qzhkr hr ne bntqrd sgd adrs vda eqzldvnqj!"
def detect(cipher)
26.times.each do |i|
decrypt = cipher.decrypt(i)
puts decrypt if WORDS.detect { |word| decrypt.include?(word) }
end
end
cipher = CaesarCipher.new(question)
detect(cipher)
cipher.sentence = response
detect(cipher)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment