如何按财产组织哈希

时间:2016-05-25 21:50:50

标签: ruby hashmap

以下是将要处理的哈希值:

{
      "flatiron school bk" => {
        :location => "NYC"
      },
      "flatiron school" => {
        :location => "NYC"
      },
      "dev boot camp" => {
        :location => "SF"
      },
      "dev boot camp chicago" => {
        :location => "Chicago"
      },
      "general assembly" => {
        :location => "NYC"
      },
      "Hack Reactor" => {
        :location => "SF"
      }
}

我需要按位置组织这些哈希值,如下所示:

{    "NYC"=>["flatiron school bk", "flatiron school", "general assembly"],
     "SF"=>["dev boot camp", "Hack Reactor"],
     "Chicago"=>["dev boot camp chicago"]}
}

1 个答案:

答案 0 :(得分:2)

您可以使用each_with_object组合成新的哈希:

hash.each_with_object({}) do |(name, data), res|
  (res[data[:location]] ||= []) << name
end

<强>解释

each_with_object 使用给定的任意对象迭代每个元素的给定块,并返回最初给定的对象。

在这种情况下,名称和数据是给定哈希中每个元素的键和值。 在(res[data[:location]] ||= []) << name中获取位置,在给定位置的结果哈希中创建数组(如果它不存在),然后将输入哈希的键放入其中。