2015-04-23 62 views

回答

5
▶ arr = [[:a, :b],[:c, :d],[:e, :f],[:g, :h]] 
▶ key, values = arr.first, arr[1..-1] 
▶ values.map { |v| key.zip v }.map &:to_h 
#⇒ [ 
# [0] { 
# :a => :c, 
# :b => :d 
# }, 
# [1] { 
# :a => :e, 
# :b => :f 
# }, 
# [2] { 
# :a => :g, 
# :b => :h 
# } 
# ] 

請注意,與此處介紹的其他解決方案不同,此函數將把第一個元素作爲關鍵字映射到任意長度的尾部。

UPD對於傳統紅寶石,不具有Array#to_h

values.map { |v| key.zip v }.map { |e| Hash[e] } 
+0

'&:to_h'不適用於ruby 2.0.0。任何其他方式? –

+0

@ahmadhamza查看更新。 – mudasobwa

+0

我只是在嘗試..謝謝你的答案。 –

1
x = [["a", "b"],["c", "d"],["e", "f"]] 
x[1..-1].map { |vs| {x[0][0] => vs[0], x[0][1] => vs[1]} } 

就像這樣。

+0

這對精確長度爲≡3的數組起作用。在這種情況下,用手構建散列更容易。 – mudasobwa

+0

wat @mudasobwa? – iced

+0

@mudasobwa你錯了 - 不要混淆在代碼中的索引[0]和[1]。代碼是正確的。 –

1
a= [['a', 'b'],['c', 'd'],['e', 'f']] 

a[1..-1].inject([]) { |sum, s| sum << {a[0][0] => s[0], a[0][1] => s[1]} } 

=> [{"a"=>"c", "b"=>"d"}, {"a"=>"e", "b"=>"f"}] 

改進:

a= [['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'k']] 
a[1..-1].inject([]) do |sum, s| 
    hash = {} 
    a[0].each_with_index { |it, i| hash.merge!({it => s[i]}) } 
    sum << hash 
end 
=> [{"a"=>"d", "b"=>"e", "c"=>"f"}, {"a"=>"g", "b"=>"h", "c"=>"k"}] 

這種方式更爲靈活。

2

我會用Array#product

arr = [[:a, :b], [:c, :d], [:e, :f]] 

arr.first.product(arr[1..-1]).map(&:to_h) 
    #=> [{:a=>:c, :b=>:d}, {:a=>:e, :b=>:f}] 

如果arr可以被修改,我們可以這樣寫:

arr.shift.product(arr).map(&:to_h) 
1

我會寫:

key = a.shift 
p a.map{|x| key.zip(x).to_h } => [{"a"=>"c", "b"=>"d"}, {"a"=>"e", "b"=>"f"}]