inthenameofmusik
inthenameofmusik

Reputation: 623

Reduce/Inject Operator in Ruby

I'm testing out the reduce/inject method and ruby and came across a command with unexpected results.

(1..2).reduce(:<<) produces #=> 4

I believe I understand what reduce and inject do but I'm not understanding the << operator.

Upvotes: 2

Views: 140

Answers (2)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

<< is Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

e.g.

10 << 2 #=> 40.

10 binary representation is 0000 1010 will be shifted to left by 2 bits and the result will be 0010 1000 which is 40

Upvotes: 1

davidrac
davidrac

Reputation: 10738

The << operator is the Binary Left Shift Operator. It will shift the bits in the binary representation of the number the amount of places you specify.

So 1 << 2 will shift all the bits of 1 left by 2 positions.

In your example code, 1 will be shifted 2 positions to the left, which is the binary representation of 4, which is the result.

Upvotes: 6

Related Questions