Search code examples
arraysrubyiteratoreachoperations

Ruby - How do you perform an operation on each item of two (maybe more) arrays and populate them in a new array?


a = [6, 7, 8, 9, 10]
b = [1, 2, 3, 4, 5]

each of array a's items are divided by each of array b's items and put into a new array called c.

c = [6, 3, 2, 2, 2]

Solution

  • a = [6, 7, 8, 9, 10]
    b = [1, 2, 3, 4, 5]
    
    c = a.zip(b).map { |e| e.reduce :/ }
    #⇒  [
    #    [0] 6,
    #    [1] 3,
    #    [2] 2,
    #    [3] 2,
    #    [4] 2
    # ]
    

    Array#zip zips the arrays together and then each element (array of 2 items zipped) is reduced with Integer#/.