From: Joel VanderWerf Date: 2006-02-07T08:03:13+09:00 Subject: Re: Method Definitions: &block vs. yield() James H. wrote: > Suppose I had two methods: > > # First method > def my_first_method(b) > yield b > end > > # Second method > def my_second_method(&block) > block.call > end to be really comparable: def my_second_method(b, &block) block.call(b) end > I know that the block in the 2nd example is converted to a Proc object, > but a Proc object (to my newb eyes) doesn't seem to hold any advantages > that might make me want to use the latter method. > > I was wondering if there are specific advantages to using the &block > convention or yield()ing a block? Is it merely a matter of preference > and or convention? Yield is lighter weight, since no Proc is created. Also, when a Proc is created, it's binding is stored, and that binding includes any variables in scope in the proc. As long as you hang on to that Proc, the values of those variables cannot be GC-ed. But with yield, you can only call the block from within the scope of the method. If you need to store it away somewhere and call it after returning, then you have to use a Proc. -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407