Newbie Question on Operator Precedence?

I need your help to understand the output of this program.

puts false or true #----> output is false. OR does not get evaluated?

if false or true
then puts 'then' #----> output is 'then'. OR gets evaluated!
else puts 'else'
end

What's the reason? Thanks for all the help, in advance.

ZT

Z T wrote:

What's the reason?

The line:

puts false or true

is equivalent to:

(puts false) or true

puts returns nil, so that statement is equivalent to:

nil or true

which evaluates to:

false or true

and the result of that is true--but since you didn't save the result in
a variable, it is discarded. Try this:

result = (puts false) or true
p result

--output:--
nil

That result may also be surprising. That's because the statement:

result = (puts false) or true

is equivalent to

(result = (puts false)) or true

puts returns nil, which gets assigned to result, and the statement
becomes:

result or true

which is equivalent to:

nil or true

which is equivalent to:

false or true

which evaluates to true--but since the result isn't stored anywhere, it
is discarded.

if false or true

That statement is equivalent to:

if (false or true)

which evaluates to:

if true

···

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

Z T wrote:

if false or true
then puts 'then' #----> output is 'then'. OR gets evaluated!
else puts 'else'
end

What's the reason? Thanks for all the help, in advance.

ZT

for the if statement it gets evaluated so it is true and "then" is
evaluated.

for puts flase or ture, I tried it. I got the same result of yours.
However, I tried puts false and true. The output was false. I am not
sure about this one.

I tried this and it gave me true

puts "#{false or true}"
It gets evaluated.

Thanks

···

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