我有这个价值
{:cat=>["cat1", "cat2", "cat3"], :dog=>["dog1", "dog2", "dog3"]}
我正在寻找从每个键中检索/移位值:
即:
获取以下内容:
[{:cat => "cat1", :dog => "dog1"}, {:cat => "cat2", :dog => "dog2"} ... etc]
我真的不确定接近这个的最佳方法,有什么建议吗?
编辑:
到目前为止,我有:
a[a.keys.first].dup.map{|c| a.map{|index, vals| vals.shift}}
# => [["cat1", "dog1"], ["cat2", "dog2"], ["cat3", "dog3"]]
虽然由于缺少钥匙而不是我想要的。
答案 0 :(得分:3)
这个怎么样?
a = {:cat=>["cat1", "cat2", "cat3"], :dog=>["dog1", "dog2", "dog3"]}
a1 = a.each_with_object({}) do |(k, vals), memo|
shifted = vals.shift
memo[k] = shifted
end
a # => {:cat=>["cat2", "cat3"], :dog=>["dog2", "dog3"]}
a1 # => {:cat=>"cat1", :dog=>"dog1"}
答案 1 :(得分:1)
不修改原始哈希:
h = {:cat=>["cat1", "cat2", "cat3"], :dog=>["dog1", "dog2", "dog3"]}
h.values.first.zip(h.values.last).map do |value_pair|
Hash[ h.keys.zip(value_pair) ]
end
# => [{:cat=>"cat1", :dog=>"dog1"}, {:cat=>"cat2", :dog=>"dog2"}, {:cat=>"cat3", :dog=>"dog3"}]
h
# => {:cat=>["cat1", "cat2", "cat3"], :dog=>["dog1", "dog2", "dog3"]}
数组#zip:http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-zip
答案 2 :(得分:1)
h = {:cat=>["cat1", "cat2", "cat3"], :dog=>["dog1", "dog2", "dog3"]}
ks = h.keys
h.values.transpose.map{|vs| Hash[[ks, vs].transpose]}
# => [
# {:cat => "cat1", :dog => "dog1"},
# {:cat => "cat2", :dog => "dog2"},
# {:cat => "cat3", :dog => "dog3"}
# ]
或者,强烈推动单线,略微牺牲速度:
h.values.transpose.map{|vs| Hash[[h.keys, vs].transpose]}
答案 3 :(得分:0)
cats_and_dogs = {:cat=>["cat1", "cat2", "cat3"], :dog=>["dog1", "dog2", "dog3"]}
cats_with_dogs = []
i = 0
cats_and_dogs[:cat].each do |e|
cats_with_dogs << {cat: cats_and_dogs[:cat][i], dog: cats_and_dogs[:dog][i]}
i+=1
end
cats_with_dogs # [{:cat=>"cat1", :dog=>"dog1"}, {:cat=>"cat2", :dog=>"dog2"}, {:cat=>"cat3", :dog=>"dog3"}]