Mastid
Mastid

Reputation: 3459

How can I map values in two different arrays as properties on an equivalent array of objects?

I have two arrays:

a = [a1, ..., an]
b = [b1, ..., bn]

I want to create an array of Objects from these arrays where an object has fields a and b. So it would look like:

o = [o1, ..., on]

where o1.a = a1 and o1.b = b1 and o2.a = a2 and o2.b = b2 and so on.

Right now, I have:

Obj = Struct.new(:a, :b)
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
objs = []
// Is there a better way of doing the following or is it okay?
a.zip(b).each do |ai|
  objs << Obj.new(ai[0], ai[1])

Upvotes: 3

Views: 144

Answers (2)

Chris Heald
Chris Heald

Reputation: 62648

In Ruby 1.9, the following works:

a = (1..10).to_a
b = (11..20).to_a
o = Struct.new(:a, :b)

a.zip(b).map {|x, y| o.new(x, y) }

# => [#<struct a=1, b=11>, #<struct a=2, b=12> ... ]

You can just pass multiple parameters to the block, and the array that would be passed to it gets expanded into those parameters, just like *args or a, b = [1, 11] would do.

Upvotes: 3

Kyle
Kyle

Reputation: 22258

a.zip(b).map { |args| Obj.new(*args) }

Per your edit:

a.zip(b).map { |(a, b)| Obj.new(a, b) }

Upvotes: 4

Related Questions