What is the difference between "or" and | in ruby?

I thought the only difference between |

and ||

where |

would be equivalent or

. But I realized that the latter is not true and now I am confused.

AMEND : I understand that this question is different from ruby bitwise or , while my question is what is the difference between bitwise and boolean operators, as pointed out here in the comments and answers. Also, in my opinion, the answers to this question were more relevant and clear to the problem itself. Marking it as a duplicate will discourage users from giving better answers.

+3


source to share


2 answers


An operator |

is a binary math operator, that is, it does a binary OR and works at the numerical level:

1 | 2
# => 3
4 | 3
# => 7
1 | 2 | 3
# => 3

      

This is because it manages the individual values ​​as if they were binary:

0b01 | 0b10
# => 3 (0b11)

      

The operator ||

is boolean, that is, it returns the first value that is boolean. Ruby only evaluates literal values nil

and false

evaluates to logically false; everything else, including 0

empty strings and arrays, is true.

So:



1 || 2
# => 1
0 || 1
# => 0

      

The operator or

works in much the same way ||

, except that it has a much lower precedence. This means that other operators are evaluated first, which can lead to some problems if you don't expect it:

a = false || true
# => true
a
# => true

a = false or true
# => true
a
# => false

      

This is because it is actually interpreted as:

(a = false) or true

      

This is due to the fact that it =

has a higher priority in the evaluation.

+4


source


||

and or

- special built-in operators. This means that they can (and do) have behavior that cannot be expressed in Ruby. In particular, ||

both or

are lax and lazy in their correct operand, whereas Ruby is actually a strict and impatient language.

OTOH, |

is just a method call like any other method call. This is nothing special. It means:

  • Strictly
  • he is impatient
  • any object can answer it, but he wants


While ||

and or

are language built-in operators, which are

  • lax in its right operand
  • lazy on its right operand
  • their behavior is hardcoded and does not depend on any particular object, it is always the same and cannot be changed.

The only difference between ||

and or

has priority: it or

has very low priority (and has the same priority as and

).

+1


source







All Articles