Group_by helps you sort items into groups based on a rule you choose. It makes it easy to organize data by categories.
Group_by for categorization in Ruby
Introduction
Syntax
Ruby
collection.group_by { |item| condition }The group_by method takes a block with a rule to decide the group for each item.
It returns a hash where keys are group names and values are arrays of items in those groups.
Examples
n.even? as the condition.Ruby
numbers = [1, 2, 3, 4, 5, 6] groups = numbers.group_by { |n| n.even? } # => {false=>[1, 3, 5], true=>[2, 4, 6]}
Ruby
words = ['apple', 'banana', 'avocado', 'blueberry'] groups = words.group_by { |w| w[0] } # => {'a'=>['apple', 'avocado'], 'b'=>['banana', 'blueberry']}
Sample Program
This program groups fruits by their first letter and prints each group with its fruits.
Ruby
fruits = ['apple', 'banana', 'apricot', 'blueberry', 'avocado'] groups = fruits.group_by { |fruit| fruit[0] } groups.each do |letter, fruit_list| puts "Fruits starting with '#{letter}':" fruit_list.each { |fruit| puts "- #{fruit}" } end
Important Notes
Group_by does not change the original collection.
The keys in the result hash come from the values returned by the block.
Summary
Group_by helps organize items into categories easily.
It returns a hash with groups as keys and arrays of items as values.
Use it when you want to sort data by a shared property.
Practice
1. What does the Ruby method
group_by do when called on an array?easy
Solution
Step 1: Understand the purpose of
Thegroup_bygroup_bymethod organizes elements by a condition and returns a hash.Step 2: Compare with other array methods
Sorting, removing duplicates, or converting to string are different methods likesort,uniq, orjoin.Final Answer:
It groups elements into a hash based on a given condition. -> Option BQuick Check:
group_by = groups hash [OK]
Hint: Remember: group_by returns a hash of grouped elements [OK]
Common Mistakes:
- Confusing group_by with sort or uniq
- Expecting an array instead of a hash
- Thinking it changes element order only
2. Which of the following is the correct syntax to group an array
nums by even or odd using group_by?easy
Solution
Step 1: Recall block syntax for group_by
The method requires a block with curly braces or do-end and a block variable.Step 2: Check each option's syntax
nums.group_by { |n| n % 2 == 0 } uses correct block with{ |n| ... }. nums.group_by(n % 2 == 0) misses block. nums.group_by do n % 2 == 0 end lacks block variable. nums.group_by ->(n) { n % 2 == 0 } uses lambda incorrectly.Final Answer:
nums.group_by { |n| n % 2 == 0 } -> Option CQuick Check:
Correct block syntax = nums.group_by { |n| n % 2 == 0 } [OK]
Hint: Use curly braces with block variable for group_by [OK]
Common Mistakes:
- Omitting block variable in block
- Passing condition as argument instead of block
- Using lambda syntax incorrectly
3. What is the output of this Ruby code?
words = ['apple', 'banana', 'avocado', 'blueberry']
groups = words.group_by { |w| w[0] }
puts groupsmedium
Solution
Step 1: Understand group_by with first letter
The block groups words by their first character, so keys are 'a' and 'b'.Step 2: Check output format of group_by
It returns a hash with keys as letters and values as arrays of words starting with that letter.Final Answer:
{"a"=>["apple", "avocado"], "b"=>["banana", "blueberry"]} -> Option DQuick Check:
group_by first char = hash with arrays [OK]
Hint: group_by returns a hash, not an array or string [OK]
Common Mistakes:
- Expecting an array instead of a hash
- Confusing keys and values in output
- Misreading output as string instead of hash
4. Identify the error in this Ruby code snippet:
numbers = [1, 2, 3, 4] groups = numbers.group_by do n n.even? end puts groups
medium
Solution
Step 1: Check block syntax for group_by
The block must have a variable to represent each element, likedo |n| ... end.Step 2: Identify the missing block variable
The code usesdo nwithout vertical bars, sonis treated as a local variable, causing error.Final Answer:
Missing block variable in the do-end block. -> Option AQuick Check:
Block variable required in do-end [OK]
Hint: Always use |variable| in do-end blocks [OK]
Common Mistakes:
- Omitting vertical bars around block variable
- Thinking even? is undefined for integers
- Believing group_by needs sorted array
5. Given an array of hashes representing people:
people = [
{name: 'Alice', age: 30},
{name: 'Bob', age: 20},
{name: 'Carol', age: 30},
{name: 'Dave', age: 20}
]
Which code correctly groups people by their age using group_by?hard
Solution
Step 1: Understand data structure and access
Each element is a hash with symbol keys like :age, so access withperson[:age].Step 2: Check each option's key access
people.group_by { |person| person[:age] } uses correct symbol key access. people.group_by { |person| person.name } and D use dot notation which doesn't work on hashes. people.group_by { |person| person['age'] } uses string key which is incorrect here.Final Answer:
people.group_by { |person| person[:age] } -> Option AQuick Check:
Hash keys accessed by symbols = people.group_by { |person| person[:age] } [OK]
Hint: Use symbol keys with [:key] to access hash values [OK]
Common Mistakes:
- Using dot notation on hashes
- Using string keys instead of symbols
- Confusing array of hashes with objects
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
