Ruby BLOCKS Explained 101

Blocks

Block is basically anonymous method that gets called from another method. If you have some code that executes passed in method like this:

def execute_method_in_block(named_method)
    named_method.call
    named_method.call
end

execute_method_in_block Proc.new {puts "Hello, blocks are cool!"}

You can write it like this using blocks:

def execute_method_in_block
    yield
    yield
end

execute_method_in_block  {puts "Hello, blocks are cool!"}

We’ve lost “Proc.new” and a method name, we are just saying

Whenever you find yield, execute block that is defined within braces.

You might be wondering what’s the fuss all about, this code is obviously not better than:

puts "Hello, blocks are cool!"
puts "Hello, blocks are cool!"

It turns out that blocks are useful for at least two things: iteration and comparison.You don’t loose any flexibility because you can send a block of code to execute at predefined placeholder position. That means that you can implement iteration only once, no matter how complicated it might be. Then you can “send” your custom logic and execute it for the each item in collection.

In the next example we have a collection that has iteration. Nothing fancy, it just goes through the whole collection, the “yield” command is really interesting

def each
  #bla bla loop, fetch item one by one
   yield item  #placeholed for a block, share "item" with block
  #bla bla loop again
end

The “yield” command is a placeholder that is telling us where we can insert our block. We can do whatever we want with collection items and if we just want to print them we can do something like this:

[1,2,3,4].each do |x|
  puts x
 end

We are using |x|. Although the name is not important it means that we can use “x” in our block, and that it is corresponding with “item” that is present after yield command.

It’s custom that you use braces for one-line-blocks, so this will also work:

[1,2,3,4].each { |x|  puts x }

In the runtime this will happen:

def each
  #bla bla loop, fetch item one by one
  puts item  # block
  #bla bla loop again
end

Point is that it can be anything you want so you don’t have to duplicate iteration logic.

That’s all for now, next time we’ll go through using block for comparison. Stay tuned…

blog comments powered by Disqus