Doing a "case" on class

H

Harry Ohlsen

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.
 
S

Shin Nishiyama

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
 
H

Harry Ohlsen

Shin said:
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



case fred

Great. That's even simpler.

Thanks for the quick response.

Harry O.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top