0

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
0

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Could remove the .each, zip takes a block. a.zip(b) { |a, b| a.age = b }
1

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 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.