Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally repeat a loop in Ruby?

Tags:

arrays

ruby

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?

like image 379
Andrea McKenzie Avatar asked Jan 26 '26 18:01

Andrea McKenzie


1 Answers

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.

like image 68
dave Avatar answered Jan 28 '26 10:01

dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!