Skip to content
instance method

Enumerable#group_by

[U] () { (Elem arg0) -> U } -> ::Hash[U, ::Array[Elem]]
() -> ::Enumerator[Elem, ::Array[Elem]]
group_by {|element| ... } → hash
group_by → enumerator

With a block given returns a hash:

  • Each key is a return value from the block.

  • Each value is an array of those elements for which the block returned that key.

Examples:

Example
g = (1..6).group_by {|i| i%3 }
g # => {1=>[1, 4], 2=>[2, 5], 0=>[3, 6]}
h = {foo: 0, bar: 1, baz: 0, bat: 1}
g = h.group_by {|key, value| value }
g # => {0=>[[:foo, 0], [:baz, 0]], 1=>[[:bar, 1], [:bat, 1]]}

With no block given, returns an Enumerator.

See also #grep_v #include? #grep #inject also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0