Method: Array#classify

Defined in:
lib/quality_extensions/array/classify.rb

#classify(&block) ⇒ Object

Classifies the array by the return value of the given block and returns a hash of => array of elements pairs.

The block is called once for each element of the array, passing the element as parameter.

Breaks an array into a hash of smaller arrays, making a new group for each unique value returned by the block. Each unique value becomes a key in the hash.

Example:
   [
     ['a', 1],
     ['a', 2],
     ['b', 3],
     ['b', 4],
   ].classify {|o| o[0]}
 =>  
   {
     "a" => [['a', 1], ['a', 2]], 
     "b" => [['b', 3], ['b', 4]]
   }


37
38
39
40
41
42
43
44
# File 'lib/quality_extensions/array/classify.rb', line 37

def classify(&block)
  hash = {}
  each do |element|
    classification = yield(element)
    (hash[classification] ||= []) << element
  end
  hash
end