Thursday, February 28

Blocks and Procs, Blocks are anonymous Procs!

Block and Procs can be very confusing! What is the difference between the two? How do you call the code? When do you use a block or a proc?

As it turns out, blocks are anonymous procs and you can use them almost interchangeably.

In the below code both yield and call work. There is a subtle difference though. You can not send the call message to the object if you don't explicitly state that the method accepts a block. Personally, I like to send the message call to the anonymous proc object myself since it makes the method signature clearer, you know there is a block being passed in. Another point of confusion is that if you want to actually pass in your proc you need to use the ampersand.


def foo(&block)
yield
block.call
end

proc = Proc.new {puts "proc"}
foo(&proc)

foo{ puts "block" }

ben@jefferson ~ $ ruby test.rb
proc
proc
block
block

0 comments: