0
0
Rubyprogramming~5 mins

Block given? check in Ruby

Choose your learning style9 modes available
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.
When you want a method to do something extra only if the user provides a block.
When you want to avoid errors if a method tries to use a block but none was given.
When you want to make your method flexible and optional for extra code.
When you want to run default code if no block is provided.
When you want to customize behavior inside a method based on the presence of a block.
Syntax
Ruby
def method_name
  if block_given?
    yield
  else
    # do something else
  end
end
Use block_given? inside a method to check if a block was passed.
Use yield to run the block if it exists.
Examples
This method says "Hello!" unless a block is given, then it runs the block instead.
Ruby
def greet
  if block_given?
    yield
  else
    puts "Hello!"
  end
end
This method runs the block 3 times if given, otherwise prints a message.
Ruby
def repeat
  if block_given?
    3.times { yield }
  else
    puts "No block provided."
  end
end
Sample Program
This program defines a method that checks if a block is given. It runs the block if present, otherwise prints a default message.
Ruby
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
OutputSuccess
Important Notes
If you call yield without a block, Ruby raises an error, so always check with block_given? first.
Blocks are a simple way to pass extra code to methods without needing to define separate methods.
You can use block_given? to make your methods more flexible and safe.
Summary
Use block_given? to check if a block was passed to a method.
Use yield to run the block inside the method.
Checking for a block helps avoid errors and makes methods more flexible.