=== with class type equality check fails

I wanted to do some decision on a variable class type so I wrote this:

case variable.class
when Fixnum, Float
puts “It’s a Fix or Float”
when String
puts “It’s a String”
end

It took me 2 hours to realize that ‘case’ and the underlying ‘===’ won’t
work here:

[26] pry(main)> a = 1.2
=> 1.2
[27] pry(main)> a.class
=> Float
[28] pry(main)> a.class == Float
=> true
[29] pry(main)> a.class === Float
=> false

based on documentation, ‘===’ should be smarter than ‘==’.
Did I miss something here?

Földes László wrote in post #1052241:

based on documentation, ‘===’ should be smarter than ‘==’.
Did I miss something here?

Yes - read the documentation again.

In the case of a Class object, the === operator means “is an instance
of”. So you should write:

case variable # not variable.class
when Fixnum

when String

end

HTH,

Brian.

Brian C. wrote in post #1052252:

Yes - read the documentation again.

Thanks,
I should have read the Class#=== instead of Float#===.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs