split a map into two maps in ruby

One way to split a map (also known as a hash) into two smaller maps in Ruby is to use the Enumerable#partition method.

Here's an example that splits a hash into two smaller hashes based on a condition:

main.rb
cities = {
  "New York" => "USA",
  "Paris" => "France",
  "Tokyo" => "Japan",
  "London" => "UK",
  "Sydney" => "Australia"
}

americas, non_americas = cities.partition { |k, v| v == "USA" || v == "Canada" }.map(&:to_h)

p americas #=> {"New York"=>"USA"}
p non_americas #=> {"Paris"=>"France", "Tokyo"=>"Japan", "London"=>"UK", "Sydney"=>"Australia"}
353 chars
13 lines

In this example, we are splitting the cities hash into two smaller hashes - americas and non_americas. We pass a block to the partition method that checks if the country is either "USA" or "Canada". This block returns true for "New York" (which is in the USA) and false for the rest.

The partition method returns an array containing two arrays - the first array contains the elements for which the block returned true and the second array contains the elements for which the block returned false. We then use map with to_h to convert these two arrays back into hashes. Finally, we store these two smaller maps into the variables americas and non_americas.

You can adjust the condition in the block to split the map in any way you want!

gistlibby LogSnag