From: Michael Lucas-Smith Date: 2002-01-18T18:18:17+09:00 Subject: Re: Proc.class vs yield Alexander Schofield wrote: > Sorry if I'm resurrecting an old thread here, but I've been away for a > while. > > >>Because this whole yield thing isn't required, but it's there. Because >>people like it. But then there is this 'only one' restriction which, >>please excuse the expression, seems totally brain dead to me. >> > > I'm not sure what you mean by restriction. It's true that the yield > syntax isn't necessary and we could just pass Proc objects around as > named arguments as in smalltalk. But for many cases it adds a lot of > visual distinction. In that test block, action block method you > mentioned couldn't you use a named argument for the test, and the yield > construct for the action? > I like yield, and the anonymous block. I see nothing wrong with it at all :) Keep it, please keep it. It's the common scenario to pass one anonymous block to a method. But what if you wanted to pass more than one block to a method? suddenly your code becomes ugly: def someMethod (p) p.call yield end someMethod proc { doSomething } { doSomethingElse } > >>I really do vote for having the compiler automatically handle the >>proc conversion for you. >> > > Just to be certain, is this syntax construct what you are looking for? > In this case the '&' makes a Proc object function like a block supplied > at the end of the method, different from when it used in a parameter > list. > > irb(main):001:0> p = proc {puts 'from proc'} > # > irb(main):002:0> def meth > irb(main):003:1> yield > irb(main):004:1> end > nil > irb(main):005:0> meth &p > from proc > nil > (sorry if someone already mentioned this) > > The nice thing about this is that if you had a method with an (*args) > parameter list, *args wouldn't swallow the &p and the yield would still > work. Also, yield is often convenient when you need a little more > flexibility with named arguments: > > def meth > yield 1, 2 > yield 3 > end > > p = proc {|one, two, three| p one, two, three} > meth &p #this will work (three is nil, then two and three are nil) > #but this next part will fail. > p.call 1, 2 > p.call 3 > #yield's also convenient when you give what would ordinarily be too many > arguments > Not really, I want to be able to write the following: def method (a,b,c) a.call b.call c.call yield end method { doA }, { doB }, { doC } { doD } instead of writing: method proc { doA }, proc { doB }, proc { doC } { doD } having to write all those 'proc's is nasty. Just purely nasty. I see no reason why the compiler couldn't be smart enough to assume the 'proc' for you. It should easily be able to tell the difference between an array and a block -- since it already does for the yieldable anonymous block Michael Lucas-Smith