Andrea McKenzie
Andrea McKenzie

Reputation: 239

How to conditionally repeat a loop in 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?

Upvotes: 3

Views: 116

Answers (1)

dave
dave

Reputation: 64657

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.

Upvotes: 6

Related Questions