Human-readable listing of array elements

My comment referred to the "won't handle <=" part. I demonstrated how it can be made to handle less than comparisons directly, i.e. without using ranges which is not exactly the same operation.

Cheers

  robert

···

On 10.12.2009 18:48, Aldric Giacomoni wrote:

Robert Klemme wrote:

2009/12/10 Aldric Giacomoni<aldric@trevoke.net>:

Marnen Laibow-Koser wrote:

Yes. �case won't handle<= conditions AFAIK.

That is a very good point, though it does handle ranges, so "case 0..1"
would fit this particular scenario.
Your elsif statement is probably better suited here though.

That point is not exactly true: while it doesn't out of the box...

c:\>irb
irb(main):001:0> RUBY_VERSION
=> "1.8.7"
irb(main):002:0> 5.times { |a| case a; when 0..2 then puts "yow" else
puts "nah" end }
yow
nah
=> 5
irb(main):003:0>

Alright.. Well then, I'm confused.

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

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. :slight_smile:

Not too difficult either, let's see....

Kind regards

  robert

···

On 12/10/2009 06:49 PM, Marnen Laibow-Koser wrote:

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/