Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q14 of 15
Ruby - Enumerable and Collection Processing
Identify the error in this code snippet:
items = ["apple", "pear", "banana"]
sorted = items.sort_by do |item|
  item.length
end
puts sorted
ANo error; code works correctly
BIncorrect block syntax for sort_by
CMissing parentheses in sort_by call
DUsing sort_by instead of sort
Step-by-Step Solution
Solution:
  1. Step 1: Check block syntax

    The block uses do |item| ... end, which is valid for sort_by.
  2. Step 2: Verify sort_by usage

    sort_by accepts a block and returns a new array sorted by item length. No syntax or logic errors.
  3. Final Answer:

    No error; code works correctly -> Option A
  4. Quick Check:

    sort_by with do-end block is valid [OK]
Quick Trick: do-end blocks work fine with sort_by [OK]
Common Mistakes:
  • Thinking parentheses are mandatory around block
  • Confusing sort_by with sort!
  • Assuming sort_by modifies original array

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes