Introduction
Blocks let you send extra instructions to a method. Checking if a block is given helps your method decide if it should run those extra instructions or not.
def method_name if block_given? yield else # do something else end end
block_given? inside a method to check if a block was passed.yield to run the block if it exists.def greet if block_given? yield else puts "Hello!" end end
def repeat if block_given? 3.times { yield } else puts "No block provided." end end
def show_message if block_given? puts "Block is given, running it:" yield else puts "No block given, running default message." end end show_message do puts "Hello from the block!" end show_message
yield without a block, Ruby raises an error, so always check with block_given? first.block_given? to make your methods more flexible and safe.block_given? to check if a block was passed to a method.yield to run the block inside the method.block_given? check inside a method?block_given?block_given? is a method and should be called with a question mark and optionally parentheses. The most common and clear syntax is block_given? without parentheses.yield keyword runs the block if it exists. The syntax if block_given? then yield end is correct and clear.def greet
if block_given?
yield
else
puts "Hello!"
end
end
greet { puts "Hi there!" }
greetdef show
yield if block_given
end
show { puts "Hello!" }block_given? requires the question mark and should be called as block_given? or block_given?(). Here it is missing the question mark.yield is correctly used and does not require arguments here. The method does not require parameters to accept a block.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?block_given? correctly to check if a block is passed before yielding.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.Pass the test and this pattern moves unknown