From: dblack@... Date: 2002-11-16T06:07:50+09:00 Subject: Re: ruby-dev summary 18613-18710 Hi -- On Sat, 16 Nov 2002, Florian Frank wrote: > On 2002-11-15 21:37:46 +0900, dblack@candle.superlink.net wrote: > > No, I mean the actual return value of the method call, which is a > > separate matter from the block. In your example, if there were no > > block, the return value would be different. In other words, given: > > > > n = [a,b,c].zip > > m = [a,b,c].zip { |x,y,z| x*y+z } > > > > n and m would not be the same. That's where I'm scratching my head > > and wondering if that's the best way. > > The first case is equivalent to the second case with the block > { |*tuple| tuple }. If no block is given, zip just uses the array of > parameters of this block. Yes, that's the very behavior that raises the question (to the extent that it is a question) about the presence/absence of the block affecting the return value of the method. Which for some reason seems anomalous to me.... I'm still not entirely sure why. I have to do some digging and refresh my memory as to how blocks with optional methods usually behave. (Hmmm, what did we do in scanf? :-) > In fact that's exacly the way I implemented zip and unzip while > converting some Haskell functions into Ruby. Haskell has zip, zip3, > zipWith and zipWith3 and all of this functions can be replaced by a > single Ruby method which even can do zipWithN: > > module Enumerable > > def zip(&block) > block ||= lambda { |*tuple| tuple } > size = nil > map { |x| x.size }.each do |s| > size ||= s > s == size or raise "zip with unequal length lists" > end > result = [] > i = 0 > catch(:stop) do (Don't you like regular Ruby iterators? :-) > tuple = [] > each do |l| > l[i] or throw :stop That test is going to prevent you from zipping arrays that have nil or false as elements, for example: a = [1,2,3] b = [4,nil,6] p [a,b].zip # [[1,4]] I notice that you've made this a method of Enumerable, rather than Array. What would the effect be of calling #zip on a non-Array Enumerable, for example a String? "abcde".zip # => ? (I gather from the original post that there was some discussion of Enumerable#zip in the Japanese list... not sure what was said, though, and I'm not clear on how it would work.) David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav