Group Hash by values in ruby

后端 未结 5 1193
广开言路
广开言路 2021-01-11 10:49

I have a hash in ruby which looks something like this:

{
  \"admin_milestones\"=>\"1\",
  \"users_milestones\"=>\"0\",
  \"admin_goals\"=>\"1\",
  \         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-11 11:39

    You can group hash by its value:

    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}
    

    It will produce a hash grouped by its values like this:

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

提交回复
热议问题