Enumerable Method

by Jim O'Neal on December 13, 2015

In this blog I will discuss an enumerable method called .group_by. I chose this method from a list of three methods available for this exercise: .group_by, .cycle, and .map. I chose .group_by because it seemed the most interesting and one that I have never used.

The .group_by method is a very useful method. The description of this method from the website ruby-doc.org is as follows: Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block and the values are arrays of elements in the collection that correspond to the key.
The syntax of the method works similar to the .each method which should be familiar to most of the readers here. The method is typically called on a list of data or an array. The important thing to remember is that .group_by will always return a hash, and the elements of the passed-in data will be the values in the hash, not the keys.

To help this method make sense, below are a few simple examples and the result when the method is run:

Example 1:

hash1 = (1..6).group_by { |i| i%3 }

hash1 = {
  1=>[1, 4],
  2=>[2, 5],
  0=>[3, 6]
}

Example 2:

test_array = [1,2,3,4,5,6]

hash2 = test_array.group_by{|x| x > 3}

hash2 = {
  false=>[1, 2, 3],
  true=>[4, 5, 6]
}

Example 3:

name_array = ["Jim", "Bob", "Kate", "Dave", "James", "Thomas", "Carrie", "Rumpelstiltskin"]

hash3 = name_array.group_by{|x| x.length}

hash3 = {
  3=>["Jim", "Bob"],
  4=>["Kate", "Dave"],
  5=>["James"],
  6=>["Thomas", "Carrie"],
  15=>["Rumpelstiltskin"]
}

Example 4:

food_array = ["Carrot Cake", "Steak", "Pumpkin Pie", "Blueberry Pie", "Hamburger", "Pizza", "Chocolate Cake", "Salad"]

hash4 = food_array.group_by do |x|
  if x.include?("Cake") || x.include?("Pie")
    "Dessert"
  else
    "Dinner"
  end
end

hash4 = {
  "Dessert"=>["Carrot Cake", "Pumpkin Pie", "Blueberry Pie", "Chocolate Cake"],
  "Dinner"=>["Steak", "Hamburger", "Pizza", "Salad"]
}