From: Marnen Laibow-Koser Date: 2009-12-11T00:03:59+09:00 Subject: Re: human-readable listing of array elements 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? array.inspect Of course, that won't get you the "and". > > 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 Interesting question. class Array # or perhaps module Enumerable def stringify(conjunction = 'and', separator = ', ') if self.size <= 1 return self.to_s elsif self.size == 2 return self.join " #{conjunction} " else array = self.dup array[-1] = [conjunction, array[-1]].join ' ' array.join separator # proper English usage has comma before 'and' end end end > end Best, --  Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org -- Posted via http://www.ruby-forum.com/.