Beast_Code
Beast_Code

Reputation: 3247

How to iterate through an array and pass each element onto a method?

Suppose I have two arrays with numbers inside. I want to iterate through both arrays and pass each element to a method that accepts 2 parameters.

x = [2,3,9,1]
y = [1,9,2,1]

def add (x,y)
  x+y
end

I want to be able to pass each element in x and y. I want to implement this in Ruby but Python or another language is fine.

Upvotes: 0

Views: 128

Answers (4)

yv84_
yv84_

Reputation: 131

>>> list(map(lambda x: add(x[0],x[1]), zip(x,y)))
[3, 12, 11, 2]

Upvotes: 1

doubleo
doubleo

Reputation: 4759

This should also do the job:

# len(a) or len(b) can be used - As both are of same length

for i in range(len(a)):
    add(a[i], b[i])

Upvotes: 1

Brionius
Brionius

Reputation: 14098

In python:

for a, b in zip(x, y):
    add(a, b)

Upvotes: 2

sawa
sawa

Reputation: 168081

In Ruby,

x.zip(y){|x, y| ... add(x, y) ...}

will do.

Upvotes: 3

Related Questions