Bird
0
0

How can you modify this method to safely call yield only if a block is given?

hard📝 Application Q8 of 15
Ruby - Blocks, Procs, and Lambdas
How can you modify this method to safely call yield only if a block is given?
def safe_call
  yield
end
Adef safe_call yield unless block_given? end
Bdef safe_call yield(true) end
Cdef safe_call yield() rescue nil end
Ddef safe_call yield if block_given? end
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to check for block presence

    Ruby provides block_given? to check if a block was passed.
  2. Step 2: Use conditional yield

    Calling yield only if block_given? prevents errors when no block is given.
  3. Final Answer:

    def safe_call yield if block_given? end -> Option D
  4. Quick Check:

    Use block_given? to safely yield [OK]
Quick Trick: Use block_given? before yield to avoid errors [OK]
Common Mistakes:
  • Using yield without checking block presence
  • Using rescue to hide errors instead of checking
  • Calling yield with wrong arguments

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes