Bird
0
0

You want a method that returns the first even number from an array or nil if none found. Which code correctly uses explicit return to stop early?

hard📝 Application Q15 of 15
Ruby - Methods
You want a method that returns the first even number from an array or nil if none found. Which code correctly uses explicit return to stop early?
def first_even(numbers)
  numbers.each do |n|
    if n.even?
      return n
    end
  end
  nil
end
AReturns nil always because return is inside loop.
BReturns all even numbers as an array.
CReturns first even number or nil, stops early with return.
DRaises error because return cannot be used in block.
Step-by-Step Solution
Solution:
  1. Step 1: Understand method logic

    The method loops over each number and checks if it is even.
  2. Step 2: Analyze explicit return usage

    When it finds an even number, it uses return n to immediately return that number and stop the method.
  3. Step 3: Check fallback return

    If no even number is found, the method returns nil after the loop.
  4. Final Answer:

    Returns first even number or nil, stops early with return. -> Option C
  5. Quick Check:

    Explicit return stops loop and returns value early = A [OK]
Quick Trick: Use return inside loop to exit method early when condition met [OK]
Common Mistakes:
  • Thinking return inside block causes error
  • Expecting all even numbers returned
  • Ignoring nil fallback return

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes