[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Weird behavior of case/when

Nicolas Desprès

7/12/2006 8:31:00 AM

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,

--
Nicolas Desprès

4 Answers

Kroeger, Simon (ext)

7/12/2006 8:44:00 AM

0



> -----Original Message-----
> From: Nicolas Desprès [mailto:nicolas.despres@gmail.com]
> Sent: Wednesday, July 12, 2006 10:31 AM
> To: ruby-talk ML
> Subject: Weird behavior of case/when
>
> 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,

case uses === which is well defined for obj === 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'

cheers

Simon

Pit Capitain

7/12/2006 8:48:00 AM

0

Nicolas Desprès schrieb:
> I'm getting a very weird result using case/when.
> (...)

Nicolas, why do you find it weird? Have you read the documentation, for
example

http://phrogz.net/ProgrammingRuby/tut_expressions.html#casee...

Regards,
Pit

Nicolas Desprès

7/12/2006 8:50:00 AM

0

On 7/12/06, Kroeger, Simon (ext) <simon.kroeger.ext@siemens.com> wrote:
>
> case uses === which is well defined for obj === 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 === but I would have never expected
that it behaves this way.

Regards,

--
Nicolas Desprès

Marcin Mielzynski

7/13/2006 7:42:00 PM

0

Nicolas Desprès wrote:
> On 7/12/06, Kroeger, Simon (ext) <simon.kroeger.ext@siemens.com> wrote:
>>
>> case uses === which is well defined for obj === 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 === but I would have never expected
> that it behaves this way.
>
> Regards,

It should behave that in a language where classes are objects :D (unlike
java where instances of java.lang.Class are just proxies to vm internals)

lopex