From: Robert Klemme Date: 2009-12-11T18:12:34+09:00 Subject: Re: human-readable listing of array elements 2009/12/11 botp : > On Thu, Dec 10, 2009 at 10:15 PM, Aldric Giacomoni wrote: >> This took me less than a minute to write, but I don't know if it's as >> elegant as it could be. Are there more "Ruby-like ways(tm)" to write >> this? >> >> def stringify array >>  return array[0] if array.size == 1 >>  string = "" >>  array.each_with_index do |element, index| >>    case index >>      when array.size - 1 # last item >>        string += " and #{element}" >>      when 0 >>        string += "#{element}" >>      else >>        string += ", #{element}" >>    end >>  end >>  string >> end >> -- > > > just joing the fun of ruby, > > C:\prg>cat test3.rb > > def stringify array >  string = "" >  array.each_with_index do |element, index| >    string << case index >                when 0 >                  "" >                when (as=array.size) - 1 # last item >                  (as < 3 ? "" : "," ) + " and " >                else >                  ", " >              end << "#{element}" >  end >  string > end > > s=[] > %w(this is a test). each do |element| >  p stringify(s<<[element]) > end > > C:\prg>ruby -W0 test3.rb > "this" > "this and is" > "this, is, and a" > "this, is, a, and test" The comma... :-) Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/