Reputation: 3476
I have some code that I am debugging that uses this operator and I'm not sure why it is used.
It appears to be appending the object to an array. If that was all I do not know why the engineer didn't simply use the '<<' operator. What is the difference?
Thanks!
Upvotes: 2
Views: 542
Reputation:
It is not always the case that <<
modifies the target: it might be the result that is of importance. Consult the API for the actual types used as to the behavior.
A bit-shift of an integer does not have a side-effect (the computation is discarded unless it is assigned/used):
a = 1
a << 2
a # => 1
a <<= 2
a # => 4
But <<
on an array does have a side-effect (and <<=
would just perform a useless assignment1 that hides the side-effect nature of the operation):
b = [1]
b << 2
b # => [1,2]
1 In rare cases, it might be "clever" with accessors to use obj.prop <<= val
for side-effecting operations as it will invoke both the getter and the setter - and the setter may contain logic. However, I use the word "clever" and not "good" here for a reason :)
Upvotes: 3
Reputation: 14565
http://www.tutorialspoint.com/ruby/ruby_operators.htm
it looks like its a bitwise left shift operation and assignment in one.
x <<= 2
is the same as
x = x << 2
Upvotes: 3