Bird
0
0

What is the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Enumerable and Collection Processing
What is the output of this Ruby code?
words = ['apple', 'banana', 'avocado', 'blueberry']
groups = words.group_by { |w| w[0] }
puts groups
A[["a", ["apple", "avocado"]], ["b", ["banana", "blueberry"]]]
B["apple", "avocado", "banana", "blueberry"]
C{"apple"=>"a", "banana"=>"b"}
D{"a"=>["apple", "avocado"], "b"=>["banana", "blueberry"]}
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes