Reputation: 57212
I'm new to ruby, and I saw this code snippet
1|2
and it returns 3
What does the |
operator actually do? I couldn't seem to find any documentation on it. Also, in this context is it referred to as the "pipe" operator? or is it called something else?
Upvotes: 26
Views: 15216
Reputation: 780
This is a bitwise operator and they work directly with the binary representation of the value.
|
mean OR. Let me show you how it works.
1|2 = 3
what happens under the hoods is:
1 = 0001
2 = 0010
--------
3 = 0011 <- result
another example:
10|2 = 10
now in binary:
10 = 1010
2 = 0010
--------
10 = 1010 <- result
Upvotes: 33
Reputation: 1502
In Ruby, "operators" are actually method calls. They are defined by each class.
1 and 2 are Fixnum and so in 1|2
pipe does "bitwise or".
Upvotes: 15
Reputation: 1434
It is the bitwise or operator.
http://www.java2s.com/Code/Ruby/Language-Basics/dobitwiseoperationsinRuby.htm
Upvotes: 2