Block is basically anonymous method that gets called from another method. If you have some code that executes passed in method like this:
You can write it like this using blocks: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!"}
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:
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.
puts "Hello, blocks are cool!"
puts "Hello, blocks are cool!"
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
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: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
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.[1,2,3,4].each do |x|
puts x
end
It’s custom that you use braces for one-line-blocks, so this will also work:
In the runtime this will happen:[1,2,3,4].each { |x| puts x }
Point is that it can be anything you want so you don’t have to duplicate iteration logic.
def each
#bla bla loop, fetch item one by one
puts item # block
#bla bla loop again
end
That’s all for now, next time we’ll go through using block for comparison. Stay tuned…