26

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?

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406

3 Answers3

32

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
roshiro
  • 770
  • 1
  • 5
  • 9
14

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".

Ruby doc

Bitwise info

nickgroenke
  • 1,472
  • 9
  • 12
  • oops, yeah, I didn't even think about bitwise or. when I saw 1|2 and the result was 3, my thought immediately went to addition so that's what confused me about it. – Jeff Storey Jun 24 '12 at 23:21
2

It is the bitwise or operator.

http://www.java2s.com/Code/Ruby/Language-Basics/dobitwiseoperationsinRuby.htm

Speed
  • 1,424
  • 1
  • 16
  • 24