Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group Hash by values in ruby

Tags:

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

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

I am trying to lookout for a solutions which can cut this hash in to two parts, one with value as 1 and other hash with value as 0.

like image 765
123 Avatar asked Sep 17 '13 05:09

123


People also ask

How do I group an array in Ruby?

The group by creates a hash from the capitalize d version of an album name to an array containing all the strings in list that match it (e.g. "Enter sandman" => ["Enter Sandman", "Enter sandman"] ). The map then replaces each array with its length, so you get e.g. ["Enter sandman", 2] for "Enter sandman" .

How do I get the hash value in Ruby?

In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.

Can a hash have multiple values Ruby?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

Can you sort a hash in Ruby?

Sorting Hashes in RubyTo sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.


2 Answers

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"]]} 
like image 93
Aman Garg Avatar answered Oct 04 '22 02:10

Aman Garg


If you want an array as answer the cleanest solution is the partition method.

zeros, ones = my_hash.partition{|key, val| val == '0'}
like image 44
hirolau Avatar answered Oct 04 '22 04:10

hirolau