Monday, July 9, 2007

Blocks vs. Procs in Ruby

It's one of the weird questions - when do you use a Proc instead of a block, and why? A discussion on the ruby-talk list about alternate block semantics in future versions of Ruby included comments from Charles Oliver Nutter of the JRuby project, which cleared things up for me:

yield is a keyword whose function depends on having access to the current call frame. Since any method you might define and call would execute in a new call frame, there's no way to provide a method that does what yield does. This is why if you ever want to pass a given block to another method, you must capture it in a block argument, and also why yielding to a block is much faster than calling a proc (since there's less overhead in yielding than in calling a free-standing proc).

My conclusion: favor blocks over Procs. I don't quite understand everything here, but the implication is that calling a free-standing Proc requires getting a different call frame, while yielding requies the call frame that you already have. This means that working with blocks fits the natural flow of the language better than working with Procs.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.