Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Blocks, Procs, and Lambdas
What will be the output of the following Ruby code?
def test_proc
  p = Proc.new { return "From Proc" }
  p.call
  return "From method"
end

puts test_proc
A"From Proc"
B"From method"
Cnil
DRuntimeError
Step-by-Step Solution
Solution:
  1. Step 1: Understand Proc return behavior

    When a Proc executes a return, it returns from the enclosing method, not just the Proc block.
  2. Step 2: Trace the code execution

    Calling p.call triggers the Proc's return, which exits the test_proc method immediately with "From Proc". The later return "From method" is never reached.
  3. Final Answer:

    "From Proc" -> Option A
  4. Quick Check:

    Proc return exits method = "From Proc" [OK]
Quick Trick: Proc return exits method; lambda return exits lambda only [OK]
Common Mistakes:
  • Thinking return exits only the Proc block
  • Expecting "From method" output
  • Confusing Proc and lambda return behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes