Ok, this did not work like I expected (because I know too little about
Ruby):
def test( obj )
case obj.class
when Array then puts "Array"
when Hash then puts "Hash"
when Class then puts "Class"
else puts "ugh"
end
end
irb(main):009:0> test Array.new
Class
=> nil
irb(main):010:0> test Hash.new
Class
=> nil
irb(main):011:0> test Class.new
Class
=> nil
Hmmm. Ok. So I figured out that case/when uses === and not ==. I’m
sure there is for a good reason but…why?
irb(main):012:0> Array === Array
=> false
irb(main):013:0> Class === Class
=> true
So it turns out that === for Class checks if the rvalue is an instance
of the lvalue and === of Object is a just ==. Is this right? Obviously
Array is not an instance of Array, but not so obviously, Class IS an
instance of Class. This makes sense but my brain is starting to hurt.
So I can write ‘test’ this way:
def test( obj )
case obj # <---- removed the '.class’
when Array then puts "Array"
when Hash then puts "Hash"
when Class then puts "Class"
else puts "ugh"
end
end
irb(main):022:0> test Array.new
Array
=> nil
irb(main):023:0> test Hash.new
Hash
=> nil
irb(main):024:0> test Class.new
Class
=> nil
Werid. Can someone help me figure out the === operator? When should I
be redefining it? In what cases should I be using it?
Michael