Group Hash by values in ruby

后端 未结 5 1197
广开言路
广开言路 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:32

    Similar with https://stackoverflow.com/a/56164608/14718545 you can use group_by but with then, in this case, you will avoid instantiating an extra variable.

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

提交回复
热议问题