1
> test = false and true => false > test => false > test = true and false #this is the point I don't understand! => false > test => true 

Why does ruby behave in this way and how would I use it correctly to not run into this problem?

1 Answer 1

10

Precedence. test = true and false means this:

(test = true) and false 

not this:

test = (true and false) 

Use parentheses as above, or && instead of and, if you want the assignment to come last:

test = true && false 
Sign up to request clarification or add additional context in comments.

2 Comments

From the github ruby styleguide : 'The and and or keywords are banned. It's just not worth it. Always use && and || instead.'
Inherited from Perl. In the beginning, there was only && and ||. But these were used both like C (as logical primtives) and like the shell (to handle success/failure). In the latter use the precedence caused surprises like my @info = stat($file) || die "error" calling stat in scalar instead of list context. The lower-precedence and/or/not were introduced to solve those headaches, but gave us new ones, and Ruby borrowed them right along with the rest of the stuff it got from Perl.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.