Monday, October 22, 2007

Ruby Language Extension: with "keyword"

Dan Yoder posted something really neat and compact on the ruby-talk mailing list:

module Kernel
 def with(object,&block)
  object.instance_eval &block

with([1,2,3]) { length } # => 3

The usage comes from Pascal and JavaScript. The performance cost of eval means you should be cautious about overusing this idiom in production code, but I definitely dig it.


  1. So, it's syntactic sugar (or is it vinegar) for "."? So now instead of the cumbersome


    I can write the much more concise and easy-to-read

    with([1,2,3]) { length }


    Maybe I'm just being dense here, or airing my ruby-noob credentials. Please enlighten me.

  2. Well, it's not the real use case. You wouldn't do that, it's just proof that it works. The real use case would be

    with(object) { some block that would normally involve typing the object's name several times }

    Like in the JavaScript link, the goal is basically, you're working in the context of this object. I think the JS one is probably the inspiration for Rails' with_scope.


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