Bird
0
0

Which Ruby code snippet correctly determines if a block was passed to a method?

easy📝 Conceptual Q2 of 15
Ruby - Blocks, Procs, and Lambdas
Which Ruby code snippet correctly determines if a block was passed to a method?
Aif yield; puts "Block present"; end
Bif block_given?; puts "Block present"; end
Cif block_given; puts "Block present"; end
Dif block; puts "Block present"; end
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct method call

    block_given? is a method and must be called with parentheses or as a method call.
  2. Step 2: Analyze options

    if block_given?; puts "Block present"; end uses block_given? correctly. if yield; puts "Block present"; end incorrectly uses yield as a condition. if block_given; puts "Block present"; end misses the question mark. if block; puts "Block present"; end uses an undefined variable block.
  3. Final Answer:

    if block_given?; puts "Block present"; end -> Option B
  4. Quick Check:

    Use block_given? with question mark [OK]
Quick Trick: Use block_given? with question mark to check block [OK]
Common Mistakes:
  • Omitting question mark in block_given?
  • Using yield as a boolean check
  • Checking undefined variable 'block'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes