use of case statement doesn't work as I expect :( help appreciated!

G

gabe

Hi all,

I have an object ( a website tester) that can return various values.
One of which is Net:HTTPOK, I want to use a case statement to evaluate
this and set a variable called 'severity', as follows:

result = TestWebsite::test( site )
case result
when Net::HTTPOK
severity = :INFO
when SocketError
severity = :ERROR
else
severity = :WARN
end

However, when Net::HTTPOK is returned, the severity variable ALWAYS
ends up as :WARN instead of :INFO.

Using IRB I have manually entered the code in as follows:=> Net::HTTPOK

Then ran the following tests:=> false

This to me just proves the result I am getting is Net::HTTPOK, but why
can't I get it to match in the case statement?

Many thanks for any help

Gabriel
 
R

rick.denatale

Hi all,

I have an object ( a website tester) that can return various values.
One of which is Net:HTTPOK, I want to use a case statement to evaluate
this and set a variable called 'severity', as follows:

result = TestWebsite::test( site )
case result
when Net::HTTPOK
severity = :INFO
when SocketError
severity = :ERROR
else
severity = :WARN
end

This form of case
case x
when y
...

is logically equivalent to:

if y === x
...

Now Net::HTTPOK is a class, and class implements === as a test of
whether the argument is an instance of the class or a subclass.

Array === [] #=> true
Array === Array #=> false

If response is really the class then you either want to use if/elsif or

case
when result == Net::HTTPOK
...
 
H

hungrylist

I think you problem is in your code the case is testing if

result.is_a? Net::HTTPOK

and not

result == Net::HTTPOK

This happens since Net::HTTPOK is a class and not an object

If you rewrite your code this way you should see the behaviour you're expecting.

result = TestWebsite::test( site )

case result.to_s
when 'Net::HTTPOK'
severity = :INFO
when 'SocketError'
severity = :ERROR
else
severity = :WARN
end

A better idea would be to have TestWebsite::test( site ) returning the
object and not the class, this way you don't need to rewrite your
original case code

Paolo
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top