Case statements and classes

In general, I love the way case statement matching works. I’m having
trouble, however, when trying this:

irb(main):001:0> case Integer
irb(main):002:1> when String then 'str’
irb(main):003:1> when Integer then 'int’
irb(main):004:1> when Array then 'arr’
irb(main):005:1> else '???'
irb(main):006:1> end
=> “???”

Any ideas, other than `if … elsif … elsif … else’? Is there any way to
make case use == instead of ===? Or something?

Chris

In general, I love the way case statement matching works. I’m having
trouble, however, when trying this:

irb(main):001:0> case Integer
irb(main):002:1> when String then ‘str’
irb(main):003:1> when Integer then ‘int’
irb(main):004:1> when Array then ‘arr’
irb(main):005:1> else ‘???’
irb(main):006:1> end
=> “???”

It’s because the more common use is to compare objects with their
classes:

case 1
when Integer then ‘int’

end

Any ideas, other than `if … elsif … elsif … else’? Is there any
way to
make case use == instead of ===? Or something?

How about using a Hash:

ClassNames = { Integer => 'int', Strin => 'str' }
ClassNames.default = '???'

Classnames[Integer]   #-> int

Cheers

Dave

···

On Thursday, April 17, 2003, at 11:55 AM, Chris Pine wrote:

In general, I love the way case statement matching works. I’m having
trouble, however, when trying this:

irb(main):001:0> case Integer
irb(main):002:1> when String then ‘str’
irb(main):003:1> when Integer then ‘int’
irb(main):004:1> when Array then ‘arr’
irb(main):005:1> else ‘???’
irb(main):006:1> end
=> “???”

It’s because the more common use is to compare objects with their
classes:

case 1
when Integer then ‘int’

end

Any ideas, other than `if … elsif … elsif … else’? Is there any
way to
make case use == instead of ===? Or something?

How about using a Hash:

ClassNames = { Integer => 'int', Strin => 'str' }
ClassNames.default = '???'

Classnames[Integer]   #-> int

Cheers

Dave

···

On Thursday, April 17, 2003, at 11:55 AM, Chris Pine wrote:

It’s because the more common use is to compare objects with their
classes:

case 1
when Integer then ‘int’

end

···

----- Original Message -----
From: “Dave Thomas” dave@pragprog.com


Oh, I know why it does what it does, and I love it the way it is.


How about using a Hash:

Well, that was a smaller example. I suppose I could use a hash and bind
classes to procs… but I have since come up with this (somewhat ugly)
trick:

irb(main):001:0> case Integer.id
irb(main):002:1> when String.id then 'str’
irb(main):003:1> when Integer.id then 'int’
irb(main):004:1> when Array.id then 'arr’
irb(main):005:1> else '???'
irb(main):006:1> end
=> “int”

Good enough for now,

Chris