From: Marnen Laibow-Koser Date: 2009-12-12T05:50:28+09:00 Subject: Re: human-readable listing of array elements Shot (Piotr Szotkowski) wrote: > Aldric Giacomoni: > >> 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? > >> string += ", #{element}" >> end >> end >> string >> end > > Couldn’t resist: > > def stringify a > a.size < 2 ? a.first.to_s : a[0..-2].join(', ') + " and #{a.last}" > end > >>> stringify [] > => "" >>> stringify ['Arthur'] > => "Arthur" >>> stringify ['Arthur', 'Ford'] > => "Arthur and Ford" >>> stringify ['Arthur', 'Ford', 'Trillian'] > => "Arthur, Ford and Trillian" >>> stringify ['Arthur', 'Ford', 'Trillian', 'Marvin'] > => "Arthur, Ford, Trillian and Marvin" > > — Shot I like it! Best, --  Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org -- Posted via http://www.ruby-forum.com/.