I'm working on creating a Caeser Cypher code and I can't figure out how to get the search loop to "return" back to "a" in my alphabet array.
Here's what I got:
def ceaser_cypher(string, num)
alphabet = ("a".."z").to_a
letters = string.split("")
letters.map!.with_index do |let,idxs|
if alphabet.include?(let)
alphabet[alphabet.index(let) + num]
end
end
letters.join("")
end
Works like a charm for most letters, but for, say, "y", and "z", they of course return nil if, say, num == 3 because there aren't three more indexes past in the alphabet array; instead of returning "b" or "c" respectively. So how do I get the loop to come around to the beginning?
You would want to do:
alphabet[(alphabet.index(let) + num) % alphabet.length]
The modulus operator will cause it to effectively "wrap" when it goes past the length of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With