Doubt regarding Topic "Short-Circuit Evaluation"


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-1o8Mb/1/4?curriculum_id=5059f8619189a5000201fbcb


Well, according to the instructions, in the code below -:

puts a || b

Ruby will evaluate a first. Since it is true, it should not evaluate b because in "true || x", doesn't matter whatever 'x' is, it will return true only. But in the output window, The result is -:

B was also evaluated!
true


false
nil

Therefore, I am wondering why was "b" evaluated at all?



#2

For this code:

puts a || b
puts "------"
puts a && b

this is the output I see:

A was evaluated!
true
------
A was evaluated!
B was also evaluated!
true

notice that B is being evaluated only in the second case when we are using the && operator. In the case of ||, B is NOT being evaluated as is evident from the output.


#3

Yeah! Now I can see the output is correct. Previously the output was as I mentioned in my post. May be they fixed it.

Thanks for your reply!


#4

I am also getting a bizarre output for this exercise. It's just a demonstration right. I didn't change the default code.

Output;

3

B was also evaluated!
true
nil

This output is unexpected.... where the heck is 3 coming from?

Code:


#5

def a
puts "A was evaluated!"
return true
end

def b
puts "B was also evaluated!"
return true
end

puts a || b
puts "------"
puts a && b


#6

Same error here plus some tests :

As you can see, our method a() is still there, and still return false. Is there some code that override script.rb before evaluation ?

When I run localy the original script, it works as expected and the one I have edited throws an error "undefined local variable or method `a' for main:Object (NameError)" which is as expected too.


#7

What I think is that in “&&” operator. . .ruby check left side… if it is false, it will not check write one. . if it is true. . it will check for right one. whats your point?


#8

Ok, I understand the output above the dotted line, but why is the ‘true’ value that is returned from the ‘a’ method being ignored when we ‘puts a && b’ ?

I expected the output to look like this:

A was evaluated!
true <– why is this one not here?
B was also evaluated!
true

:confused: