Skip to content

Instantly share code, notes, and snippets.

@caioertai
Last active February 8, 2023 00:17
Show Gist options
  • Save caioertai/2bcb430d1bc799bd41b23391fe8c67a0 to your computer and use it in GitHub Desktop.
Save caioertai/2bcb430d1bc799bd41b23391fe8c67a0 to your computer and use it in GitHub Desktop.
Ruby Day 3 Livecode - Iterators and Blocks | Caesar's salad (encryption)
def encrypt(message, encryption_key = -3)
# Creates an alphabet array using a range
alphabet = ("A".."Z").to_a
# Converts the message (a String) into an upcased
# array of letters
letters = message.upcase.chars
# Iterate (with #map) over each letter
letters.map do |letter|
# Finds the index of the current letter in the alphabet
# this returns an integer if the letter is found
# or nil if not found
index = alphabet.index(letter)
# Checks if the letter was found or not
if index.nil?
# Returns (implicitly) just the same letter if not found
# (this will be the case for spaces and punctuation marks)
letter
else
# If the letter was indeed found we:
# - Use the encryption key on the index
# - and do a modulo (remainder) operation to limit
# - the number to the amount of letter in the alphabet
new_index = (index + encryption_key) % alphabet.size
# Get and return (implicitly) the new equivalent letter
# from the alphabet
alphabet[new_index]
end
end.join # joins the array of letters into a string again
end
# The decrypt method uses the same encyption key
def decrypt(message, encryption_key = -3)
# But calls encrypt again with its key sign (+/-) reversed
encrypt(message, encryption_key * -1)
end
p decrypt("QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD", -3)
p decrypt(
"FK ZOVMQLDOXMEV, X ZXBPXO ZFMEBO, XIPL HKLTK XP ZXBPXO'P ZFMEBO, QEB PEFCQ ZFMEBO, ZXBPXO'P ZLAB LO ZXBPXO PEFCQ, FP LKB LC QEB PFJMIBPQ XKA JLPQ TFABIV HKLTK BKZOVMQFLK QBZEKFNRBP. FQ FP X QVMB LC PRYPQFQRQFLK ZFMEBO FK TEFZE BXZE IBQQBO FK QEB MIXFKQBUQ FP OBMIXZBA YV X IBQQBO PLJB CFUBA KRJYBO LC MLPFQFLKP ALTK QEB XIMEXYBQ. CLO BUXJMIB, TFQE X IBCQ PEFCQ LC 3, A TLRIA YB OBMIXZBA YV X, B TLRIA YBZLJB Y, XKA PL LK. QEB JBQELA FP KXJBA XCQBO GRIFRP ZXBPXO, TEL RPBA FQ FK EFP MOFSXQB ZLOOBPMLKABKZB.",
-3
)
require_relative "encrypt"
describe "#encrypt" do
it "returns a string" do
actual = encrypt("hi").class
expected = String
expect(actual).to eq(expected)
end
it "returns an encrypted message" do
actual = encrypt("QUICK")
expected = "NRFZH"
expect(actual).to eq(expected)
end
it "returns an encrypted message" do
actual = encrypt("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG")
expected = "QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD"
expect(actual).to eq(expected)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment