2013-04-30 59 views
3

我有兩個陣列:如何將兩個不同數組中的值映射爲等效對象數組上的屬性?

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

我想,其中對象具有字段ab創建從這些陣列對象的陣列。因此,它看起來像:

o = [o1, ..., on] 

其中o1.a = a1o1.b = b1o2.a = a2o2.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
a.zip(b).map { |args| Obj.new(*args) } 

根據您的編輯:

a.zip(b).map { |(a, b)| Obj.new(a, b) } 
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]會做的那樣。

相關問題