Вопрос

I was playing in Pry and came across this:

20] pry(main)> ('X' && 'O') == 'X'
=> false
[22] pry(main)> ('O' && 'X') == 'X'
=> true

With this, I was trying to check if both values within the parentheses are the same as the value on the right. The result of the second one though tells me I'm missing something.

It seems like it's returning the value of the last comparison ('X' == 'X'), but I was under the impression that && would stop as soon as it found the first false?

I can see why the order would matter in general but I thought by wrapping them in () they would be checked as one condition?

Это было полезно?

Решение

but I was under the impression that && would stop as soon as it found the first false?

You are correct. But that didn't happen in your either of the examples.

In your both example 'O' and 'X', are string objects, which has truthy value.

In the example ('X' && 'O') == 'X', ('X' && 'O') gives "O", and it is being compared to "X", which is false of-course. Thus you got false.

In other one ('O' && 'X') == 'X', ('O' && 'X') gives "X", and which is then being compared to "X", and of-course it should be true. Thus you got true in your PRY.

Note : In Ruby all objects has truthy value, except nil and false.

While using &&, it will be continuing evaluation, all its expression, till it is getting an expression which evaluated as falsy.

Другие советы

in ruby &&,and it'll check first value if it's there,it.ll go to next value,first value false or nil it will return the value.

foo = :foo
bar = nil

a = foo and bar
# => nil
a
# => :foo

a = foo && bar
# => nil 
a
# => nil

a = (foo and bar)
# => nil
a
# => nil

(a = foo) && bar
# => nil
a
# => :foo
> a = true && false
=> false 
> a
=> false 
> a = true and false
=> false 
> a
=> true   
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top