Bird
0
0

Identify the error in this Ruby code that tries to find the first negative number:

medium📝 Debug Q14 of 15
Ruby - Enumerable and Collection Processing

Identify the error in this Ruby code that tries to find the first negative number:

numbers = [3, 5, -2, 7]
result = numbers.find do |n|
  n < 0
end
puts result
AThere is no error; the code works correctly.
BThe variable <code>n</code> is not defined in the block.
CThe block syntax is incorrect; should use curly braces.
DThe method <code>find</code> does not accept a block.
Step-by-Step Solution
Solution:
  1. Step 1: Check block syntax

    The do...end block with variable n is valid syntax for find.
  2. Step 2: Confirm method usage

    find accepts a block and returns the first element matching n < 0.
  3. Final Answer:

    There is no error; the code works correctly. -> Option A
  4. Quick Check:

    Valid block syntax and method usage = There is no error; the code works correctly. [OK]
Quick Trick: Remember: do-end blocks are valid for find [OK]
Common Mistakes:
  • Thinking only curly braces work for blocks
  • Assuming variable must be declared outside block
  • Believing find can't take blocks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes