Syntax
items.group_by { |item| key_for(item) }Examples
Grouping Records with group_by
Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
words = %w[ant bear cat dog]
groups = words.group_by { |word| word.length }
p groups[3]
p groups[4]- Expected output: ["ant", "cat", "dog"] ["bear"]
- The block computes an integer key for every word. All words of length three share one array in encounter order.
Best practices
- Use tally when only counts are needed and retaining every element would waste memory.
- Avoid expensive key computation inside the grouping block when it can be prepared once.
Runtime & versions
Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Ruby documentation