Concept Flow - Block given? check
Method called
Check if block given?
Yield block
Continue method
End
The method checks if a block is given. If yes, it runs the block with yield; if no, it skips yield and continues.
def greet if block_given? yield else puts "No block given" end end greet { puts "Hello!" }
| Step | Action | block_given? check | Branch Taken | Output |
|---|---|---|---|---|
| 1 | Call greet with block | true | Yes (yield block) | Hello! |
| 2 | Yield block execution | - | - | Hello! printed |
| 3 | Method ends | - | - | - |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| block_given? | false | true | true | true |
Use block_given? inside a method to check if a block was passed.
If true, use yield to run the block.
If false, skip yield or run alternative code.
Prevents errors when yield is called without a block.
Syntax:
if block_given?
yield
else
# no block code
end