From: Robert Klemme Date: 2009-12-11T00:35:16+09:00 Subject: Re: human-readable listing of array elements 2009/12/10 Aldric Giacomoni : > 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. Oh no. Pascal is responsible for lispish solutions - I'm not. :-) > I like your first one - it feels more elegant than mine. The second one > feels a little too convoluted. Yep. > 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. I just felt #slice deserved a mention because it is so rarely seen. Initially I also thought about using #slice! which cannot be done with #[]. But then you would either modify the argument or have to dup the Array. > Thanks for the further examples, I'll > remember them (and possibly even use them someday!) You're welcome! Thanks for the opportunity to play around a bit. :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/