From: matz@... (Yukihiro Matsumoto) Date: 1999-07-26T03:08:13+09:00 Subject: [ruby-talk:00529] Re: Another way for this? And a new proposal! Hi, In message "[ruby-talk:00526] Another way for this? And a new proposal!" on 99/07/25, Clemens Hintze writes: |I don't know, why following is not possible directly: | | blk1 = { |e| p(e) } |or | blk1 = do |e| p(e) end | |perhaps difficult to parse, matz? Yes. { |e| p(e) } is too close to hash to distinguish for parser. |Okay we would have on check more, but we would have the |advantage, that the method could get both, a Proc instance or a |block for execution. So it would be possible to do both: | | : | .each{ |e| p e } | : |and | : | blk = proc{ |e| p e } | : | .each blk | : | |wouldn't that be nice? Or is there any problem with these, that I |have not seen until yet? You can always do def each(blk=lambda) ... end to receive blocks as the normal argument. By this way, you can supply the Proc as the argument to the method, which also works as iterator. |Unfortunately the following seems not to be possible at the moment: | | : | def block; (iterator?) ? proc : nil end | | def each(aBlock=block) | @list1.each aBlock | @list2.each aBlock | end | : | |The method `block' will not be executed in the context of `each'! Is |that designed so? That's desined so. Use lambda/proc/Proc.new instead. They work as you want, I guess. You can pass block as the special block argument like: blk = proc{ |e| p e } .each(&blk) BTW, by historical reason, the block treatment is tuned up for yield. The method using yield runs several times faster than one using Proc object. That's one of the reasons why we can't avoid yield fully. |Let me stress it once more: We would not only be able to iterate |using a block, but also using a Proc instance. IMO, it would make |Ruby more flexible. Furthermore it would bring block and Proc |instances more close to each other. | |What do you think about? I think the block argument &block (in invoking method) is the right tool for you. You can pass any Proc object as the block. binary_handler = proc{ <...> } text_handler = proc{ <...> } : handler = textfile(filename) ? text_handler : binary_handler File::open filename, &handler matz.