L's World
L's World

Reputation: 465

Assign each array element attribute with a value from another array respectively

I am trying to assign each person an age value from a list with same size.

class Person
 attr_accessor :age
end

a = [person1, person2, person3, person4, person5]
b = [1,2,3,4,5]

How can I do the assignment below using a neat way(without using index i)?

i = 0
a.each do |p|
  p.age = b[i]
  i += 1
end

Upvotes: 0

Views: 76

Answers (2)

potashin
potashin

Reputation: 44581

You can use index (as each Person instance is going to be unique):

a.each { |ai| ai.age = b[a.index(ai)] }

Demonstration

P.S. I would go with the approach introduced by @ardavis, using just zip:

a.zip(b) { |a, b| a.age = b }

Upvotes: 1

Mark Thomas
Mark Thomas

Reputation: 37507

If they are guaranteed to be the same length, then you can use zip:

a.zip(b).each do |p, age|
  p.age = age
end

As @ardavis pointed out, zip takes a block so you can remove the .each.

I know you asked for a solution without an index, but note that your code can be made neater even with an index. In Ruby, you don't need to define and increment your own index. Instead, you can use with_index like so:

a.each.with_index do |p, i|
  p.age = b[i]
end

Upvotes: 4

Related Questions