📜 ⬆️ ⬇️

Ruby '&&' and 'and' Operators

At one interview, I was asked: “when you write in Ruby, do you use the operator 'and' or two ampersand '&&' to denote the logical 'AND'?”. In fact, out of old habit, I always put two ampersands '&&' and never thought about it. So he answered, they told me, "Good."

And you are not looking at cut can clearly explain the difference between 'and' and '&&' in Ruby?


Suppose we have the following code.
total = user_messages.empty? and user_messages.total


And what value will total ? Number of posts by the user? Not! The thing is, the interpreter will read it like this:
(total = user_messages.empty?) and user_messages.total


')
So total becomes true or false . This is not what you wanted at all! Why it happens? Just because there is an operator priority table in Ruby . Having studied it, we understand that you can use the && operator.
The next two lines of code are exactly the same.

total = user_messages.empty? && user_messages.total
total = (user_messages.empty? && user_messages.total)



Similar story with or operators and || .
Look at your code ...

PS And here's another example for the final understanding (or misunderstanding)
irb(main):001:0> x=1
=> 1
irb(main):002:0> y=2
=> 2
irb(main):003:0> x || y && nil
=> 1
irb(main):004:0> x or y and nil
=> nil

Source: https://habr.com/ru/post/94566/


All Articles