Ruby optionally passing a block to a function

This post shows how to pass a block to a method, how to pass a parameter to a block, and how to check if a block exists.

First the source code we are going to use:

def say(message, &block)
 block.call(message)
end
def greet(message, &some_block)
 if block_given? 
 say(message, &some_block) 
 else 
 say(message){|msg| puts "Default behavior: #{msg}"} 
 end
end
puts "No blocks given:"
greet("Greetings!")
puts "Block given:"
greet("Greetings!"){|m| puts "My block says: #{m}"}

Output:

No blocks given:
Default behavior: Greetings!
Block given:
My block says: Greetings!

Let’s walk through this step by step:

First let’s look at the greet function:

def greet(message, &some_block)

This defines a function that takes a parameter and a block. Next we check if the caller has passed a block, if not we will provide our default block:

if block_given? 
 say(message, &some_block)

For details on block_given, see http://apidock.com/ruby/Kernel/block_given%3F
Notice that there is a & when passing some_block.

else
 say(message){|msg| puts "Default behavior: #{msg}"}
end

If the caller doesnt pass any blocks, we can pass a default block.
|msg| denotes that the block takes one parameter. When you write your functions, it is possible to define a block that doesn’t take any parameter, just skip the |x| part entirely.

Next we will look at the say function which calls the block:

def say(message, &block)
 block.call(message)
end

block.call calls the block and passes it the parameter. That’s it!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s