[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Doing a "case" on class

Harry Ohlsen

7/10/2003 8:23:00 AM

This hits me every time I try to do it and definitely feels non-POLS to me!

Can someone explain why this isn't kosher ...

fred = 123

case fred.class
when Fixnum
puts "Yippee!"

# when <various other types>

else
puts "I don't know what to do with #{fred.class}"
end

I get "I don't know what to do with Fixnum".

I would have thought that fred.class returns a constant instance of Class, namely Fixnum. I would have thought that the explicit "when Fixnum" is comparing it against the same constant instance of Class. Hence, I'd expect it to choose that when clause.

What's really going on?

If I've just lost the plot (it's happened more than once :-) what's the right way to do this kind of thing?

(Obviously, in the real code, the variables I'm do the #class on isn't a constant).

Thanks in advance,

Harry O.



2 Answers

Shin Nishiyama

7/10/2003 8:50:00 AM

0

Hi,

case does not use == but === when comparision, and
irb(main):032:0> Fixnum == Fixnum
=> true
irb(main):033:0> Fixnum === Fixnum
=> false

because
$ ri Module#===
------------------------------------------------------------- Module#===
mod === anObject -> true or false
------------------------------------------------------------------------
Case Equality---Returns true if anObject is an instance of mod or
one of mod''s descendents. Of limited use for modules, but can be
used in case statements to classify objects by class.

so, you shuould code like

> fred = 123
>
case fred
> when Fixnum
> puts "Yippee!"
>
> # when <various other types>
>
> else
> puts "I don''t know what to do with #{fred.class}"
> end


Shin Nishiyama

Harry Ohlsen

7/10/2003 8:52:00 AM

0

Shin Nishiyama wrote:
> Hi,
>
> case does not use == but === when comparision, and
> irb(main):032:0> Fixnum == Fixnum
> => true
> irb(main):033:0> Fixnum === Fixnum
> => false

Ah!

> so, you shuould code like
>
>
>> fred = 123
>>
>
> case fred
>
>> when Fixnum
>> puts "Yippee!"

Great. That''s even simpler.

Thanks for the quick response.

Harry O.