Bird
Raised Fist0
Rubyprogramming~20 mins

Group_by for categorization in Ruby - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1. What does the Ruby method group_by do when called on an array?
easy
A. It converts the array into a string.
B. It groups elements into a hash based on a given condition.
C. It removes duplicate elements from the array.
D. It sorts the array in ascending order.

Solution

  1. Step 1: Understand the purpose of group_by

    The group_by method organizes elements by a condition and returns a hash.
  2. Step 2: Compare with other array methods

    Sorting, removing duplicates, or converting to string are different methods like sort, uniq, or join.
  3. Final Answer:

    It groups elements into a hash based on a given condition. -> Option B
  4. Quick 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
A. nums.group_by(n % 2 == 0)
B. nums.group_by do n % 2 == 0 end
C. nums.group_by { |n| n % 2 == 0 }
D. nums.group_by ->(n) { n % 2 == 0 }

Solution

  1. Step 1: Recall block syntax for group_by

    The method requires a block with curly braces or do-end and a block variable.
  2. 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.
  3. Final Answer:

    nums.group_by { |n| n % 2 == 0 } -> Option C
  4. Quick 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 groups
medium
A. [["a", ["apple", "avocado"]], ["b", ["banana", "blueberry"]]]
B. ["apple", "avocado", "banana", "blueberry"]
C. {"apple"=>"a", "banana"=>"b"}
D. {"a"=>["apple", "avocado"], "b"=>["banana", "blueberry"]}

Solution

  1. Step 1: Understand group_by with first letter

    The block groups words by their first character, so keys are 'a' and 'b'.
  2. 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.
  3. Final Answer:

    {"a"=>["apple", "avocado"], "b"=>["banana", "blueberry"]} -> Option D
  4. Quick 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
A. Missing block variable in the do-end block.
B. group_by cannot be used with do-end blocks.
C. The method even? does not exist for integers.
D. The array must be sorted before using group_by.

Solution

  1. Step 1: Check block syntax for group_by

    The block must have a variable to represent each element, like do |n| ... end.
  2. Step 2: Identify the missing block variable

    The code uses do n without vertical bars, so n is treated as a local variable, causing error.
  3. Final Answer:

    Missing block variable in the do-end block. -> Option A
  4. Quick 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
A. people.group_by { |person| person[:age] }
B. people.group_by { |person| person.name }
C. people.group_by { |person| person['age'] }
D. people.group_by { |person| person.age }

Solution

  1. Step 1: Understand data structure and access

    Each element is a hash with symbol keys like :age, so access with person[:age].
  2. 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.
  3. Final Answer:

    people.group_by { |person| person[:age] } -> Option A
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard