20

我在 ruby​​ 中有一个哈希,看起来像这样:

{
  "admin_milestones"=>"1",
  "users_milestones"=>"0",
  "admin_goals"=>"1",
  "users_goals"=>"0", 
  "admin_tasks"=>"1", 
  "users_tasks"=>"0",
  "admin_messages"=>"1",
  "users_messages"=>"0",
  "admin_meetings"=>"1",
  "users_meetings"=>"0"
}

我正在尝试寻找一种解决方案,该解决方案可以将此哈希分成两部分,一个值为 1,另一个值为 0。

4

5 回答 5

39

您可以按其值对哈希进行分组:

h1 = {
  "admin_milestones"=>"1",
  "users_milestones"=>"0",
  "admin_goals"=>"1",
  "users_goals"=>"0", 
  "admin_tasks"=>"1", 
  "users_tasks"=>"0",
  "admin_messages"=>"1",
  "users_messages"=>"0",
  "admin_meetings"=>"1",
  "users_meetings"=>"0"
}

h2 = h1.group_by{|k,v| v}

它将产生一个按其值分组的哈希,如下所示:

h2 = {"1"=>[["admin_milestones", "1"], ["admin_goals", "1"], ["admin_tasks", "1"], ["admin_messages", "1"], ["admin_meetings", "1"]], 
"0"=>[["users_milestones", "0"], ["users_goals", "0"], ["users_tasks", "0"], ["users_messages", "0"], ["users_meetings", "0"]]} 
于 2013-09-17T05:22:55.683 回答
7

如果您想要一个数组作为答案,最干净的解决方案是分区方法。

zeros, ones = my_hash.partition{|key, val| val == '0'}
于 2013-09-17T15:07:29.567 回答
5

您应该group_bykeys数组上使用并将值用作分组元素:

h1 = {
  "admin_milestones"=>"1",
  "users_milestones"=>"0",
  "admin_goals"=>"1",
  "users_goals"=>"0", 
  "admin_tasks"=>"1", 
  "users_tasks"=>"0",
  "admin_messages"=>"1",
  "users_messages"=>"0",
  "admin_meetings"=>"1",
  "users_meetings"=>"0"
}

# group_by on the keys, then use the value from the hash as bucket
h2 = h1.keys.group_by { |k| h1[k] }

puts h2.inspect

返回从值到键数组的散列:

{
    "1" => [
        [0] "admin_milestones",
        [1] "admin_goals",
        [2] "admin_tasks",
        [3] "admin_messages",
        [4] "admin_meetings"
    ],
    "0" => [
        [0] "users_milestones",
        [1] "users_goals",
        [2] "users_tasks",
        [3] "users_messages",
        [4] "users_meetings"
    ]
}
于 2019-05-16T08:55:19.437 回答
3

只是Hash.select

h1.select { |key, value| value == '0' } #=> {"users_milestones"=>"0", "users_goals"=>"0", ...}
h1.select { |key, value| value == '1' } #=> {"admin_milestones"=>"1", "admin_goals"=>"1", ...}

返回值取决于您的 Ruby 版本。Ruby 1.8 返回一个数组数组,而 Ruby 1.9 返回一个哈希值,如上例所示。

于 2013-09-17T07:14:03.893 回答
0

https://stackoverflow.com/a/56164608/14718545类似,您可以使用,group_bythen在这种情况下,您将避免实例化额外的变量。

{
  "admin_milestones" => "1",
  "users_milestones" => "0",
  "admin_goals" => "1",
  "users_goals" => "0",
  "admin_tasks" => "1",
  "users_tasks" => "0",
  "admin_messages" => "1",
  "users_messages" => "0",
  "admin_meetings" => "1",
  "users_meetings" => "0"
}.then { |h| h.keys.group_by { |k| h[k] } }
{"1"=>["admin_milestones", "admin_goals", "admin_tasks", "admin_messages", "admin_meetings"],
 "0"=>["users_milestones", "users_goals", "users_tasks", "users_messages", "users_meetings"]}
于 2020-11-27T09:41:59.907 回答