0
0
Rubyprogramming~3 mins

Why Block given? check in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your method could know when you want it to do something extra--and when not to--without breaking?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
def greet
  yield
end

greet # Error if no block given
After
def greet
  if block_given?
    yield
  else
    puts 'Hello!'
  end
end

greet # Works fine with or without block
What It Enables

You can write methods that adapt smoothly whether or not extra instructions (blocks) are provided, making your code smarter and safer.

Real Life Example

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.

Key Takeaways

Without checking, calling a missing block causes errors.

block_given? safely detects if a block is present.

This makes methods flexible and prevents crashes.