1

我有这个价值 {:cat=>["cat1", "cat2", "cat3"], :dog=>["dog1", "dog2", "dog3"]}

我希望从每个键中检索/移位值:

IE:

得到以下内容:

[{: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"]] 

虽然由于缺少钥匙而不是我想要的。

4

4 回答 4

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"}
于 2012-12-21T11:23:00.260 回答
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

于 2012-12-21T11:41:41.190 回答
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]}
于 2012-12-21T11:59:36.233 回答
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"}] 
于 2012-12-21T11:23:54.893 回答