按红宝石中的值分组哈希值

时间:2013-09-17 05:10:35

标签: ruby-on-rails ruby

我在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。

5 个答案:

答案 0 :(得分:29)

您可以按其值分组哈希:

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

答案 1 :(得分:6)

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

zeros, ones = my_hash.partition{|key, val| val == '0'}

答案 2 :(得分: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返回一个哈希,如上例所示。

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

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