Bird
0
0

Which code correctly implements this behavior?

hard📝 Application Q15 of 15
Ruby - Blocks, Procs, and Lambdas
You want to write a Ruby method process_items that takes an array and optionally a block. If a block is given, it should yield each item to the block; otherwise, it should return the array unchanged. Which code correctly implements this behavior?
Adef process_items(arr) arr.each { |item| yield item if block_given? } end
Bdef process_items(arr) if block_given? arr.each { |item| yield item } else arr end end
Cdef process_items(arr) if block_given arr.each { |item| yield item } else arr end end
Ddef process_items(arr) arr.each { |item| yield item } end
Step-by-Step Solution
Solution:
  1. Step 1: Check block presence correctly

    def process_items(arr) if block_given? arr.each { |item| yield item } else arr end end uses block_given? correctly to check if a block is passed before yielding.
  2. Step 2: Handle both cases properly

    If a block is given, it yields each item; otherwise, it returns the original array unchanged, matching the requirement.
  3. Step 3: Review other options for errors

    def process_items(arr) arr.each { |item| yield item } end always yields without checking block presence, causing error if no block given. def process_items(arr) if block_given arr.each { |item| yield item } else arr end end misses question mark in block_given. def process_items(arr) arr.each { |item| yield item if block_given? } end yields conditionally inside each, but block_given? inside the each block always returns false so no yielding occurs, though it returns the array.
  4. Final Answer:

    def process_items(arr) if block_given? arr.each { |item| yield item } else arr end end -> Option B
  5. Quick Check:

    Check block_given? before yield and return array if no block [OK]
Quick Trick: Check block_given? before yield; else return array [OK]
Common Mistakes:
  • Not checking block_given? before yield
  • Missing question mark in block_given
  • Returning nil instead of array when no block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes