As its name suggests, the .group_by method is used to group a collection by the results of a block of code that is passed to the method. The method 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. Here's the example given in ruby docs, where the block evaluates the integers in the range 1..6, and sorts the results based on performing modulo 3 on each integer in the range: key 0 is given values of 3 and 6, because these two integers return 0 for modulo 3; key 1 gets 1 and 4, and 2 gets 2 and 5.
(1..6).group_by { |i| i%3 } #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
The .group_by method can also utilize a ternary in the block of code, giving more options for how to sort the results of the block. The string on the left side of the colon is the hash that evaluates to true, and the string on the right evaluates to false. In the array below, the array elements that evaluate to true (i.e., true for the method item.even?) will go into a hash with a key title "even". False will go in the "odd" hash. Note the question mark to the left of "even", denoting the use of the ternary.
integers = [1, 2, 5, 7, 3, 6, 10, 25, 48, 99, 32]
integers.group_by {|item| item.even? ? "even" : "odd" }
{"odd"=>[1, 5, 7, 3, 25, 99], "even"=>[2, 6, 10, 48, 32]}
You can also use .group_by with strings, to search for whether an array of strings contains a certain word or character. Again, the ternary can be utilized if desired.
strings = ["this", "is", "a", "string", "of", "words"]
strings.group_by { |word| word.include?("of") }
{false=>["this", "is", "a", "string", "words"], true=>["of"]}
strings.group_by { |word| word.include?("o") ? "includes the letter o" : "does not include letter o" }
{"does not include letter o"=>["this", "is", "a", "string"], "includes the letter o"=>["of", "words"]}