2

我有一个这样的数组数组:

[[1,"A"], [1,"B"], [2,"C"], [2,"D"]]

我想把结果变成这样的哈希:

1 => {results => ["A","B"]}, 2 => {results => ["C","D"]}

我尝试使用“group_by”方法,但无法将其放入此表单。最有效的方法是什么?

有任何想法吗?

4

4 回答 4

2

这是你想要的吗?

irb(main):001:0> a=[[1,"A"], [1,"B"], [2,"C"], [2,"D"]]
=> [[1, "A"], [1, "B"], [2, "C"], [2, "D"]]

irb(main):002:0> h={}
=> {}

irb(main):003:0> a.each { |k,v| h[k] ||= []; h[k] << v }
=> [[1, "A"], [1, "B"], [2, "C"], [2, "D"]]

irb(main):004:0> h
=> {1=>["A", "B"], 2=>["C", "D"]}

或者,如果你真的想要一个带有“结果”键的散列表:

irb(main):003:0> a.each { |k,v| h[k] ||= {}; h[k]['result'] ||= []; h[k]['result'] << v }
=> [[1, "A"], [1, "B"], [2, "C"], [2, "D"]]
irb(main):004:0> h
=> {1=>{"result"=>["A", "B"]}, 2=>{"result"=>["C", "D"]}}
于 2012-04-12T23:25:01.527 回答
2

对于单线恋人:

a = [[1,"A"], [1,"B"], [2,"C"], [2,"D"]]
a.inject(Hash.new { |h, k| h[k] = {"results" => []} }) { |h, e| h[e.first]["results"] << e.last; h }
于 2012-04-12T23:49:20.867 回答
1

我不确定你为什么想要那个内在的“结果”词,但这里是如何得到你想要的:

the_list = [[1,"A"], [1,"B"], [2,"C"], [2,"D"]]
#=> [[1, "A"], [1, "B"], [2, "C"], [2, "D"]]

by_key = the_list.group_by(&:first)
#=> {1=>[[1, "A"], [1, "B"]], 2=>[[2, "C"], [2, "D"]]}

as_result_hash = by_key.map do |key, matches|
  [key, {'results'=>matches.map(&:last) }]
end
#=> [[1, {"results"=>["A", "B"]}], [2, {"results"=>["C", "D"]}]]

final = Hash[*as_result_hash.flatten(1)]
#=> {1=>{"results"=>["A", "B"]}, 2=>{"results"=>["C", "D"]}}

听起来您已经弄清楚了 group_by 的基本用法 - 您可以获得一组按某个键分组的结果。

下一步是将这些结果映射到您想要的格式。为此,我们只需映射 by_key 字典,返回原始键和映射结果。

这将返回一个数组,因此我们使用Hash[*array.flatten(1)]它来将其转换回字典。


如果你不需要内在的“结果”,你可以这样做:

as_result_hash = by_key.map do |key, matches|
  [key, matches.map(&:last)]
end
#=>  [[1, ["A", "B"]], [2, ["C", "D"]]]
于 2012-04-12T23:28:37.723 回答
1
a = [[1,"A"], [1,"B"], [2,"C"], [2,"D"]]
Hash[a.group_by(&:first).map{ |k, v| [k, {"results" => v.map(&:last)}]}]
于 2012-04-13T14:19:04.883 回答