From: Simon Strandgaard <0bz63fz3m1qt3001@...> Date: 2003-06-09T20:59:36+09:00 Subject: Re: [RCR] join block On Mon, 09 Jun 2003 11:21:35 +0900, Joel VanderWerf wrote: > > I don't have any compelling examples. It's just that if someone said > "Now join takes a block", this is what I would guess it would do: [snip] > But that's just POLS for me, and IANYM. POLS depends on your preferences and intuition.. I guess peoples intuition differs. 'collect-join' seems most intuitive to me :-) How about both ideas (cjoin+pjoin) at the same time ? > expand -t2 c.rb class Array alias :oldjoin :join def pair_join(&block) lhs = first res = rhs = "" self[1..-1].each do |rhs| res += lhs.to_s + block.call(lhs, rhs) lhs = rhs end res + rhs.to_s end def collect_join(sep=$,, &block) collect { |y| block.call(y) }.oldjoin(sep) end def join(sep=$,, &block) return oldjoin(sep) if not block_given? return pair_join(&block) if block.arity == 2 collect_join(sep, &block) end end def test_join puts "A: {"+[1,2,3,"a","b",5,"c"].join { |x, y| (x.class == y.class) ? "," : "} {" }+"}" puts "B: "+[1,2,3].join(", ") { |v| "(#{v})" } puts "C: "+[1,2,3].join { |v| "K#{v}O" } puts "D: "+[1,2,3].join("+") puts "E: "+[1,2,3].join end test_join > ruby c.rb A: {1,2,3} {a,b} {5} {c} B: (1), (2), (3) C: K1OK2OK3O D: 1+2+3 E: 123 > -- Simon Strandgaard