From: Joel VanderWerf Date: 2009-07-06T07:45:50+09:00 Subject: Re: to_proc and Proc/block conversion with & Russ McBride wrote: > Thanks. Interesting discussion. > >> given &expr, if expr is a Proc object, use it as >> the block; if not, call to_proc on it. > ... and then use the resulting proc as a block. > > Maybe the best way to think of & is a a proc/block converter, which, > if called on something that is neither looks first for a to_proc method > before > performing its conversion. That still makes & sound like an operator method that can be called on an object to produce a different object, though. Blocks are syntactic entities, Procs are semantic entities (a.k.a. values, objects), and & is a way of relating them. The conversion from one class to another is kind of distracting here, because it really only needs to happen in the special cases like &:sym . The & is really more like variable assignment ( = ) in ruby rather than an operator, in that '=' affects bindings (another syntax-semantics relation) but does not operate on objects. This is something that often trips up people coming to ruby from C et al. >> The only use I can think of for this feature[1] is if you want to >> conditionally instantiate the Proc, as in: >> >> def defer time >> if time < Time.now >> yield >> else >> pr = Proc.new >> # store pr somewhere and schedule it for execution >> end >> end > > But, you could just do something like this, right? > > def defer(time, &some_block) > if time < Time.now > yield # or some_block.call > else > pr = some_block > # store pr somewhere and schedule it for execution > end > end Sure, that works, but it always instantiates a Proc (the &some_block does that), even if the yield branch is taken. It's not a big difference, since instantiation and GC are not usually bottlenecks, but it's still something to be aware of. > Cheers, > Russ > > P.S. Joel, I seen now why you were inclined toward Rhodes. :-) Ruby everywhere :-) -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407