From: Dan Doel Date: 2003-08-12T10:42:46+09:00 Subject: Re: using case with classes Michael Garriss wrote: > 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 > Looking at the Ruby Class/Library reference at: http://www.rubycentral.com/ref/ Which might not be updated for 1.8, but whatever... === is the case equality operator. So you should redefine it to make your class act appropriately in case statements. For example, the Range class redefines it so that Range === obj tests to see if obj is contained in range, so you can do: case 50 when 1..10 then foo when 11..100 then bar end For Regexps, === is the same as =~. Most of the time === is the same as ==, but Module redefines === to mean is rvalue an instance of lvalue, or of a descendant of lvalue, which is where Class gets it from, I assume. Hope this helps. - Dan