Ruby: Understanding Enumerable#group_by
June 12, 2015
We have learned about Array and Hash, but it's just half way. Each of them have own methods for adding, deleting and accessing data. Enumerable methods are the bunch of methods for manipulatinf with Array and Hash. Enumerable gives us lots of useful ways of doing something to every element of a collection object(array, hash) Let's look at the method #group_by: 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. If no block is given an enumerator is returned.
Enumerable#group_by and Arrays
names = ["Julia", "Maxim", "Kate", "Natascha", "Oleg"]
=> ["Julia", "Maxim", "Kate", "Natascha", "Oleg"]
names.group_by {|name| name.length}
=> {5=>["Julia", "Maxim"], 4=>["Kate", "Oleg"], 8=>["Natascha"]}
Explanations
Each name is passed to the block. The result of block is the length of names, and this result is the group into which the name will go.
Enumerable#group_by and Hashes
food = {"Julia" => "fish", "Oleg" => "beef", "Anton" => "pasta", "Nata" => "fish", "Dima" => "chiken", "Kate" => "pasta"}
=> {"Julia"=>"fish", "Oleg"=>"beef", "Anton"=>"pasta", "Nata"=>"fish", "Dima"=>"chiken", "Kate"=>"pasta"}
food.group_by {|key, value| value}
=> {"fish"=>[["Julia", "fish"], ["Nata", "fish"]], "beef"=>[["Oleg", "beef"]], "pasta"=>[["Anton", "pasta"], ["Kate", "pasta"]], "chiken"=>[["Dima", "chiken"]]}
Explanations
In this example we group the people by the food