ruby - Why `z || y == 0` does not return what I expect? -



ruby - Why `z || y == 0` does not return what I expect? -

so taking ruby course of study in codecademy , write code

z = 39 y = 39 if z && y != 39 print "god if prints this, code failure!" elsif z || y == 0 print "dont print code" else print "success!" end

and reason runs elsif , says "dont print code" can explain me?

you have 2 things understand here: how && works , how ruby convert object true/false.

how && works:

you write:

if z && y != 39

you expect ruby interpret this:

if (z != 39) && (y != 39)

but ruby interpret this:

if (z) && (y != 39)

convert object true / false

any ruby object not nil or false evaluate true. in case, have:

if z && y != 39

which is:

if true && false # z not nil, true, , y == 39 sec part false

which of course of study evaluate false.

then

if z || y == 0

which is:

if true || false # z still not nil, y != 0 sec part false

true || false evaluate true, "dont print code" outputted.

ruby variables if-statement

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -