From: "Brian Schröder" Date: 2005-08-13T17:04:41+09:00 Subject: Re: cartesian product - next to last version On 12/08/05, walter a kehowski wrote: > Hello, > > Yielding the values is certainly a good idea, but it makes the code a > lot bigger. Anyhow, here is the recursive, yielding version. > > def cartprod(base, *others) > if block_given? > if others.empty? > base.each{|a| yield [a]} > else > base.each do | a | > cartprod(*others) do | b | > yield [a, *b] > end > end > end > nil # <--Why? > else > return base.map{|a|[a]} if others.empty? > others = cartprod(*others) > base.inject([]) { | r, a | others.inject(r) { | r, b | r << ([a, > *b]) } } > end > end > > ## Question: Why the nil? > because otherwise the function would return the base array when invoked with a block. And that would not make any sense for method chaining. Nil will invoke an exception if a chained method is called upon it. regards, Brian -- http://ruby.brian-schroeder.de/ Stringed instrument chords: http://chordlist.brian-schroeder.de/