0

What will the variables 'roses' and 'violets' contain after the following statements are executed?

roses = "blue" && "red" violets = "blue" and "red" 

I expected roses = "red", violets = "blue", as the precendece order of operators is:

  1. &&
  2. =
  3. and

But the irb shows both of them as "red". Any Explanations?

2 Answers 2

3

Don't confuse assigned value and overall value of the expression. Both lines (as whole expressions) evaluate to "red" because there's no short-circuit there and "red" is the last expression evaluated. See for yourself:

roses = "blue" && "red" # => "red" violets = "blue" and "red" # => "red" roses # => "red" violets # => "blue" 

Going further, let's place some parentheses, according to precedence

violets = "blue" and "red" 

becomes

(violets = "blue") and "red" 

becomes

("blue") and "red" 

becomes

"red" 

That's how `violets' gets assigned "blue", but the entire expression evaluates to "red".

Sign up to request clarification or add additional context in comments.

1 Comment

I guess that was just carelessness on my part to not check the actual values stored. Anyways thanks for the help.
2
  • Keep in mind that && and || operator should be used for boolean expressions evaluation,and/or for control flow evaluations. source:- ruby-style-guide

  • &&, and, ||, or all are Short-circuit operators in Ruby. But or has lower precedence than ||;and has has lower precedence than &&. source:- Boolean operators in various languages


That said,source:- Operator Precedence Table-

  • && and || has higher precedence than =.Thus your expression roses = "blue" && "red" is actually becomes roses = ("blue" && "red")

  • = has higher precedence than and and or.Thus your expression violets = "blue" and "red" is actually becomes (violets = "blue") and "red"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.