From: Robert Klemme Date: 2009-12-11T07:10:07+09:00 Subject: Re: human-readable listing of array elements On 12/10/2009 06:49 PM, Marnen Laibow-Koser wrote: > Benoit Daloze wrote: >> As written in "Programming Ruby 1.9", >> You can really use case as if ... elsif ... else ... end >> >> So, in our case: >> >> 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 >> >> becomes: >> >> case >> when self.size <= 1 >> return self.to_s >> when 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 >> > > Thanks, I had forgotten about that too. Me, too. >> Well, that's not especially better I think, but it looks cool and a >> little >> less 'procedural' to me. > > It's no less procedural, and in fact it uses another line of code for no > advantage that I can see. The advantage for me is that "case" conveys a different notion: I am reminded of SQL's case which is an expression, i.e. you get a single value out of several based on conditions after "where". "if elsif else end" is more about executing different procedural sequences. The difference is less technical and more informal. > If you truly want this to look less procedural, I think you'd need to > somehow implement a polymorphic dispatch based on Array.size...but let's > not go there. :) Not too difficult either, let's see.... Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/