1

私はこの価値を持っています {: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"]] 

キーが不足しているため、私が望むものではありませんが。

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"]}

Array#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 に答える