Difference between "and" : "&&" in Ruby

and v/s &&

Many people seem to prefer using and instead of && in Ruby, as it sounds more like speech.

However, do note that it’s slightly different from using &&. The difference is important enough that I think you should avoid using and.

&& (double ampersand) vs and
The difference is that && has higher precedence. This means that it will get evaluated before and.

So, we end up with weird stuff in some situations. This is perhaps most likely to cause weirdness when using the ternary operator, as it is evaluated before and. Here’s a real life example:

>> a = true
>> b = false

# 1
>> a and b ? 'hello' : '**silence**'
=> "**silence**"

# 2
>> a && b ? 'hello' : '**silence**'
=> "**silence**"

# 3
>> b and a ? 'hello' : '**silence**'
=> false  # oops

# 4
>> b && a ? 'hello' : '**silence**'
=> "**silence**"

So, clearly in the third case is the problem

What’s going on is that the order that the code is being evaluated in is changing the result.

So, here is what happens in case 3 (note that the same thing is happening in case one, but we would not have noticed it).

1) ternary: a ? ‘hello’ : ‘silence’ #=> “hello”
2) and: b and ‘hello’ #=> false and hello
3) => false

Whereas, in cases two and four, we have

1) &&: b && a #=> false
2) false ? ‘hello’

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Difference between Validations, Callbacks and Observers