From: Jamis Buck Date: 2004-10-21T04:12:50+09:00 Subject: Re: each with separator Charles Mills wrote: > On Oct 20, 2004, at 11:05 AM, Michael Neumann wrote: > >> Hi, >> >> I know we had a similar thread in the past about first/last-element >> detection. >> >> In Smalltalk there's #do:separateBy: which basically works like >> each+join combined, but in an imperative fashion. >> >> Now I tried to implement: >> >> [1,2,3].separate_by { puts "-" }.each {|obj| >> puts obj >> } >> >> desired output: >> >> 1 >> - >> 2 >> - >> 3 >> > > Here is another solution your probably not interested in: > > module Enumerable > def separate_by(&block) > ary = [] > each_with_index do |obj, i| > ary << block.call if i > 0 > ary << obj > end > ary > end > end > Another esoteric solution, which came to me while reading the above solution: module Enumerable def separate_by(&block) class << block; def to_s; call; end; end inject( [] ) { |a,i| a << block unless a.empty?; a << i } end end puts [ 1, 2, 3 ].separate_by { "-" } - Jamis -- Jamis Buck jgb3@email.byu.edu http://www.jamisbuck.org/jamis