Blocks and Functions in Ruby

Cristiano - June 20, 2015

Now we will consider blocks and how to pass them to functions. Type the example_blocks.rb and execute it.

#example_blocks.rb
def a_method *args, &block
  p args
  block.call
end

a_method 0, 2, 4, 6 do
  puts "hello world"
end

Output:

$ ruby example_blocks.rb
[0, 2, 4, 6]
hello world

So we call a_methodand pass on arguments 0, 2, 4, 6. This will be collected in *args variable as an array.

Now let’s see the entries starting with do and end with end and in between you can have as many statements as you want, in other words it is a block of code.
We just have a statement puts "hello world" , and that’s it. This block of code will go into the &block variable.
Now note the block.call statement in a_method, we call the block by using just block.call and not &block.call , this is important.
When we use call method on a block the block gets executed and we get the output hello world printed out.

Now let’s see another example where we can pass a variable to a block. Type in the example below and execute it.

#example_blocks_1.rb
def a_method *args, &block
  p args
  block.call 6
end

a_method 0, 2, 4, 6 do |number|
  puts "hello world\n" * number
end

Output:

$ ruby example_blocks_1.rb
[0, 2, 4, 6]
hello world
hello world
hello world
hello world
hello world
hello world

Note that in the a_method definition, we have called the block by using block.call 6. Where
does the number 6 go? 6 actually gets stored in number. Inside the block we multiply "hello world\n" by number and print it out.