0
0
Rubyprogramming~20 mins

Group_by for categorization in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Group_by Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of group_by with string length
What is the output of this Ruby code using group_by to categorize words by their length?
Ruby
words = ['cat', 'dog', 'bird', 'fish']
groups = words.group_by { |word| word.length }
puts groups
A{"cat"=>[3], "dog"=>[3], "bird"=>[4], "fish"=>[4]}
B{"cat"=>3, "dog"=>3, "bird"=>4, "fish"=>4}
C[[3, ["cat", "dog"]], [4, ["bird", "fish"]]]
D{3=>["cat", "dog"], 4=>["bird", "fish"]}
Attempts:
2 left
💡 Hint
Remember, group_by returns a hash where keys are the result of the block and values are arrays of elements.
🧠 Conceptual
intermediate
1:30remaining
Understanding group_by return type
What type of object does Ruby's group_by method return when called on an array?
AA hash with keys as group criteria and values as arrays of grouped elements
BA single array with grouped elements concatenated
CAn array of arrays
DA string representation of grouped elements
Attempts:
2 left
💡 Hint
Think about how you would access groups by their category after using group_by.
🔧 Debug
advanced
2:00remaining
Fix the error in group_by usage
This Ruby code tries to group numbers by even or odd but raises an error. What is the cause?
Ruby
numbers = [1, 2, 3, 4]
groups = numbers.group_by do |n|
  if n % 2 == 0
    'even'
  else
    'odd'
  end
end
puts groups
ANo error, code runs correctly
BTypeError because group_by expects a symbol argument
CSyntaxError due to missing 'end' for the block
DNameError because 'groups' is undefined
Attempts:
2 left
💡 Hint
Check if all blocks and conditionals are properly closed with end.
Predict Output
advanced
2:00remaining
Output of group_by with nested arrays
What is the output of this Ruby code that groups nested arrays by their first element?
Ruby
pairs = [[1, 'a'], [2, 'b'], [1, 'c'], [2, 'd']]
groups = pairs.group_by { |pair| pair[0] }
puts groups
A{1=>[[1, "a"], [1, "c"]], 2=>[[2, "b"], [2, "d"]]}
B{[1, "a"]=>1, [2, "b"]=>2, [1, "c"]=>1, [2, "d"]=>2}
C[[1, [[1, "a"], [1, "c"]]], [2, [[2, "b"], [2, "d"]]]]
D{1=>["a", "c"], 2=>["b", "d"]}
Attempts:
2 left
💡 Hint
Remember that group_by keeps the original elements grouped by the key returned from the block.
🚀 Application
expert
3:00remaining
Count words by their first letter using group_by
Given an array of words, which code correctly uses group_by to count how many words start with each letter?
Awords.group_by(&:first).map { |k, v| [k, v.size] }
Bwords.group_by { |w| w[0] }.map { |k, v| [k, v.length] }.to_h
Cwords.group_by { |w| w[0] }.transform_values(&:count)
Dwords.group_by { |w| w[0] }.count
Attempts:
2 left
💡 Hint
After grouping, you need to convert the grouped hash to a hash of counts.