Search code examples
rubyarrayscomparison

Ruby Looping Arrays over Eachother


I have two different arrays and I need a method to return to me the following:

array_1 = [1,2,3]
array_2 = ["a","b","c","d","e","f","g"]

def letter_to_number()
 #what goes here?
end

letter_to_number("g") #return 1
letter_to_number("a") #return 1
letter_to_number("b") #return 2
letter_to_number("f") #return 3

I'm not happy with any of the ways I came up with how to do this. I feel like there may be an easier way.


Solution

  • If I understand it correctly, you mean get the number like this:

    array1(repeat):  1 2 3 1 2 3 1 2 3
    array2:          a b c d e f g 
    

    You can get the letter's index in array_2, calculate the modulus (%) by the length of the array_1, and get the value in array_1 with this index:

    array_1[array_2.index("g") % array_1.length]
    # => 1
    

    I'll leave how to make a method like this to you.