Group Hash by values in ruby

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

    Just 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", ...}
    

    The return value depends on your Ruby version. Ruby 1.8 returns a array of arrays, whereas Ruby 1.9 returns a hash like in the example above.

提交回复
热议问题