What if your method could know when you want it to do something extra--and when not to--without breaking?
Why Block given? check in Ruby? - Purpose & Use Cases
Imagine you write a method that sometimes needs extra instructions from the user, but other times it works fine on its own. Without a way to check if those extra instructions are given, your method might crash or behave unexpectedly.
Manually guessing if extra instructions (blocks) are provided can lead to errors or complicated code. You might try to call a block that doesn't exist, causing your program to stop suddenly. This makes your code fragile and hard to maintain.
Ruby's block_given? method lets you easily check if a block was passed to your method. This way, you can safely decide whether to run the block or skip it, making your code more flexible and error-free.
def greet yield end greet # Error if no block given
def greet if block_given? yield else puts 'Hello!' end end greet # Works fine with or without block
You can write methods that adapt smoothly whether or not extra instructions (blocks) are provided, making your code smarter and safer.
Think of a greeting method that says a default hello if no special message is given, but uses a custom message if you provide one as a block.
Without checking, calling a missing block causes errors.
block_given? safely detects if a block is present.
This makes methods flexible and prevents crashes.