0
0
Rubyprogramming~5 mins

Group_by for categorization in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AAn array sorted by the block's return value
BA hash grouping elements by the block's return value
CA single element from the array
DA boolean indicating if grouping was successful
How would you group an array of numbers into 'positive' and 'negative' using group_by?
Anumbers.group_by { |n| n > 0 ? :positive : :negative }
Bnumbers.group_by(&:positive?)
Cnumbers.group_by { |n| n.abs }
Dnumbers.group_by { |n| n < 0 }
If you group words by their length using group_by, what will the keys of the resulting hash be?
AThe length of each word
BThe first letter of each word
CThe words themselves
DThe last letter of each word
What happens if the block passed to group_by returns nil for some elements?
AThose elements are ignored
BThose elements are grouped under an empty string key
CAn error is raised
DThose elements are grouped under the <code>nil</code> key
Which of these is a valid use of group_by?
A[1,2,3,4].group_by
B[1,2,3,4].group_by(2)
C[1,2,3,4].group_by { |n| n % 2 }
D[1,2,3,4].group_by(&:to_s)
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.