Dan Yoder posted something really neat and compact on the ruby-talk mailing list:
module Kernel
def with(object,&block)
object.instance_eval &block
end
end
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.
Monday, October 22, 2007
Subscribe to:
Post Comments (Atom)













So, it's syntactic sugar (or is it vinegar) for "."? So now instead of the cumbersome
ReplyDelete[1,2,3].length
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.
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
ReplyDeletewith(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.