From: Aldric Giacomoni Date: 2009-12-11T00:01:46+09:00 Subject: Re: human-readable listing of array elements Robert Klemme wrote: > By using String#<< your code will become more efficient because you do > not create new String objects all the time. Thanks :) > > For the fun of it here are two other solutions: > > irb(main):026:0> def stringify array > irb(main):027:1> lead = array.slice 0...-1 > irb(main):028:1> lead.empty? ? array.last.to_s : [lead.join(", "), > array.last].join(" and ") > irb(main):029:1> end > > irb(main):039:0> def stringify array > irb(main):040:1> tail = array.slice -2..-1 > irb(main):041:1> tail ? (array.slice(0...-2) << tail.join(" and > ")).join(", ") : array.first.to_s > irb(main):042:1> end > > Note, I don't claim that this is necessarily more rubyish. :-) Your solutions *stink* of LISP, but maybe that's only because you're .. er.. processing lists. I like your first one - it feels more elegant than mine. The second one feels a little too convoluted. I also find that using 'slice' is too wordy, and usually just settle for array[0...-1] or array[-2..-1] -- but clearly that's just preference. Thanks for the further examples, I'll remember them (and possibly even use them someday!) -- Posted via http://www.ruby-forum.com/.