What is the difference "case && if"?


#1

Hello there,

Sometime I feel like I understood Ruby and sometime I think its too
freaky???

Here is example what I don’t get?

This work as it is…

if request.post?
#do something

When I try to put it inside case, it doesn’t work???

case request
when post
#doesn’t work
when post?
#doesn’t work
end

This is confusing??

Regards,
Jamal


#2

The statements you are making are not the same

if request.post?
is either true or false

case request
when post
is akin to saying:
if request == post

If you want to use a case statement, then try something like:
case request.post?
when true

do something

when false
…etc.

There’s not much need for a case statement when evaluating true or
false, though.


Posted via http://www.ruby-forum.com/.


Toby Privett
<< rorbar.com >>


#3

The case statement compares the target of the case (request) with each
when item (post, post?) using ===.

So what you’ve done there is compared the request object to something
called post. I would think that that would be a no method error…

But anyway, try

case request.method
when :post
# do something
when :get
# do something else
end

That’s untested and off the cuff however…

b


#4

Ben M. wrote:

case request.method
when :post
# do something
when :get
# do something else
end

That’s untested and off the cuff however…

Thanks for that, I figure it out when I posted this topic


#5

toby privett wrote:

The statements you are making are not the same

if request.post?
is either true or false

case request
when post
is akin to saying:
if request == post

If you want to use a case statement, then try something like:
case request.post?
when true

do something

when false

Thanks, this help me to understand the difference…

So request.post? is either (true or false)

and request.method == post
check if method post, get or put is used etc :smiley: