Ruby分组哈希

4xy9mtcn  于 2023-04-05  发布在  Ruby
关注(0)|答案(2)|浏览(119)
people = [
  { "name" => "Mary", "sport" => "squash", "fruit" => "blackberry" },
  { "name" => "Lauren", "sport" => "squash", "fruit" => "orange" },
  { "name" => "Isla", "sport" => "weightlifting", "fruit" => "banana" },
  { "name" => "Sam", "sport" => "cycling", "fruit" => "orange" },
  { "name" => "Govind", "sport" => "squash", "fruit" => "banana" },
  { "name" => "Awad", "sport" => "weightlifting", "fruit" => "kiwi" },
  { "name" => "Will", "sport" => "cycling", "fruit" => "blackberry" }
]

sport = {
  squash: [],
  weightlifting: [],
  cycling: []
}

根据人们所选择的运动来分组,最简单的方法是什么?

I.e.

sport = {
  squash: ["Mary", "Lauren", "Govind"],
  weightlifting: ["Isla", "Awad"],
  cycling: ["Sam", "Will"]
}

事实上,哈希里面有哈希,这让我很困惑。我现在正在玩下面的,但还没有雪茄。

sport[:squash].push(people.select {|k,v| k if v == "squash"})
rta7y2nd

rta7y2nd1#

像这样的吗

people.group_by { |person| person['sport'] }
      .transform_values { |people| people.map { |person| person['name'] } }
=> {"squash"=>["Mary", "Lauren", "Govind"], "weightlifting"=>["Isla", "Awad"], "cycling"=>["Sam", "Will"]}

我已经使用了group_by和transform_values,阅读了关于它们的文档。group_by是在Enumerable上调用的(这是ArrayHash和其他模块中包含的模块),transform_values是在Hash上调用的。一次执行一个方法以更好地理解发生了什么。

q7solyqu

q7solyqu2#

您可以按如下方式填写散列sport

people.each { |g| sport[g["sport"].to_sym] << g["name"] }
sport
  #=> {:squash=>["Mary", "Lauren", "Govind"],
  #    :weightlifting=>["Isla", "Awad"],
  #    :cycling=>["Sam", "Will"]}

如果sport的密钥是未知的,并且要从people导出,则可以按如下方式进行。

people.each_with_object({}) do |g,sport|
  key_sym = g["sport"].to_sym
  sport[key_sym] = [] unless sport.key?(key_sym)
  sport[key_sym] << g["name"]
end
  #=> {:squash=>["Mary", "Lauren", "Govind"],
  #    :weightlifting=>["Isla", "Awad"],
  #    :cycling=>["Sam", "Will"]}

常见的是以以下两种方式之一缩短:

people.each_with_object({}) do |g,h|
  (h[g["sport"].to_sym] ||= []) << g["name"]
end

people.each_with_object(Hash.new { |h,k| h[k] = [] }) do |g,h|
  h[g["sport"].to_sym] << g["name"]
end

后者使用Hash::new的形式,使用一个块。

相关问题