Bird
0
0

Given this code, what will be the output?

hard📝 Application Q15 of 15
Ruby - Blocks, Procs, and Lambdas
Given this code, what will be the output?
def create_proc
  Proc.new { |x| x.nil? ? 'No value' : x * 10 }
end

my_proc = create_proc
puts my_proc.call(nil)
puts my_proc.call(5)
Anil\n50
BError\n50
CNo value\n50
DNo value\n5
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the Proc logic and trace both calls

    The Proc checks if x is nil; if yes, returns 'No value', else returns x * 10. Calling with nil returns 'No value'. Calling with 5 returns 5 * 10 = 50.
  2. Final Answer:

    No value\n50 -> Option C
  3. Quick Check:

    nil -> 'No value', 5 -> 50 [OK]
Quick Trick: Proc can handle nil with conditional inside block [OK]
Common Mistakes:
  • Expecting error when passing nil
  • Forgetting ternary condition inside Proc
  • Assuming multiplication by 10 applies to nil

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes