Recall & Review
beginner
What does the
group_by method do in Ruby?It groups elements of a collection based on the result of a block, returning a hash where keys are the group criteria and values are arrays of elements in each group.
Click to reveal answer
beginner
How do you use
group_by to categorize numbers as even or odd?You pass a block that returns
:even or :odd based on each number. For example: <br>numbers.group_by { |n| n.even? ? :even : :odd }Click to reveal answer
beginner
What type of object does
group_by return?It returns a Hash where each key is a group label and each value is an array of elements belonging to that group.
Click to reveal answer
intermediate
Can
group_by be used on arrays of strings? Give an example.Yes! For example, grouping words by their first letter: <br>
words.group_by { |word| word[0] } groups words by their starting character.Click to reveal answer
beginner
What happens if the block passed to
group_by returns the same value for multiple elements?All those elements are grouped together under the same key in the resulting hash.
Click to reveal answer
What does
group_by return when called on an array?✗ Incorrect
group_by returns a hash where keys are group labels and values are arrays of grouped elements.How would you group an array of numbers into 'positive' and 'negative' using
group_by?✗ Incorrect
Option A correctly uses a block returning symbols :positive or :negative based on the number's sign.
If you group words by their length using
group_by, what will the keys of the resulting hash be?✗ Incorrect
Grouping by length means the keys are integers representing word lengths.
What happens if the block passed to
group_by returns nil for some elements?✗ Incorrect
Elements with block result
nil are grouped under the nil key in the hash.Which of these is a valid use of
group_by?✗ Incorrect
Options C and D are valid uses of group_by: C uses a block to group numbers by remainder when divided by 2 (even/odd), and D uses a symbol to proc to group by string representation.
Explain how the
group_by method works in Ruby and give a simple example.Think about how you can sort items into labeled boxes based on a rule.
You got /3 concepts.
Describe a real-life situation where you could use
group_by to organize data.Imagine sorting your books or clothes into categories.
You got /3 concepts.