Weird behavior of case/when

N

Nicolas Desprès

I'm getting a very weird result using case/when.

$ cat test.rb
def test(a)
case a.class
when Class
puts "class"
when String
puts "string"
else
puts "else"
end
end

test(Float)
test("hello")
test(42)
$ ruby test.rb
class
class
class
$ ruby --version
ruby 1.8.4 (2005-12-24) [i686-linux]

I would have exepected the following output:

class
string
else

Does anyone have an explanation about this issue?

Cheers,

--=20
Nicolas Despr=E8s
 
K

Kroeger, Simon (ext)

=20
-----Original Message-----
From: Nicolas Despr=E8s [mailto:[email protected]]=20
Sent: Wednesday, July 12, 2006 10:31 AM
To: ruby-talk ML
Subject: Weird behavior of case/when
=20
I'm getting a very weird result using case/when.
=20
$ cat test.rb
def test(a)
case a.class
when Class
puts "class"
when String
puts "string"
else
puts "else"
end
end
=20
test(Float)
test("hello")
test(42)
$ ruby test.rb
class
class
class
$ ruby --version
ruby 1.8.4 (2005-12-24) [i686-linux]
=20
I would have exepected the following output:
=20
class
string
else
=20
Does anyone have an explanation about this issue?
=20
Cheers,

case uses =3D=3D=3D which is well defined for obj =3D=3D=3D class.=20
What you do is checking the class of a.class which is a class itself.

To make it short: use 'case a' instead of 'case a.class'

cheers

Simon
 
N

Nicolas Desprès

case uses =3D=3D=3D which is well defined for obj =3D=3D=3D class.
What you do is checking the class of a.class which is a class itself.

To make it short: use 'case a' instead of 'case a.class'

Thank you. I knew that case uses =3D=3D=3D but I would have never expected
that it behaves this way.

Regards,

--=20
Nicolas Despr=E8s
 

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,770
Messages
2,569,586
Members
45,088
Latest member
JeremyMedl

Latest Threads

Top