using case with classes

M

Michael Garriss

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
 
R

Ryan Pavlik

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

try this:

def test( obj )
case obj
when Array then puts "Array"
when Hash then puts "Hash"
when Class then puts "Class"
else puts "ugh"
end
end

Unfortunately the behavior above is still annoying; in this case you
have an object to work with, but I've run into a number of cases
where I have only a class, and I just have to use a big "if" block.
 
G

Gavin Sinclair

def test( obj )
case obj
when Array then puts "Array"
when Hash then puts "Hash"
when Class then puts "Class"
else puts "ugh"
end
end

How about

def test(obj)
if [Array, Hash, Class].include?(obj.class) then
puts obj.class.to_s
else
puts "ugh"
end
end

I suspect that the case statement may be faster.

How about

def test(obj)
puts \
case obj
when Array, Hash, Class then obj.class
else; "ugh"
end
end

?

Gavin
 

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
474,102
Messages
2,570,645
Members
47,246
Latest member
TemekaLutz

Latest Threads

Top