3

我有两个数组:

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

我想从这些数组中创建一个对象数组,其中一个对象具有字段ab. 所以它看起来像:

o = [o1, ..., on]

在哪里o1.a = a1o1.b = b1o2.a = a2等等o2.b = b2

现在,我有:

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])
4

2 回答 2

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

根据您的编辑:

a.zip(b).map { |(a, b)| Obj.new(a, b) }
于 2013-04-30T03:12:22.137 回答
3

在 Ruby 1.9 中,以下工作:

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> ... ]

您可以将多个参数传递给块,然后将传递给它的数组扩展为这些参数,就像*argsa, b = [1, 11]将做的那样。

于 2013-04-30T03:17:13.643 回答