I am quite new to Ruby and am wondering about the <<
operator. When I googled this operator, it says that it is a Binary Left Shift Operator given this ex
Ruby is an object-oriented language. The fundamental principle of object orientation is that objects send messages to other objects, and the receiver of the message can respond to the message in whatever way it sees fit. So,
a << b
means whatever a
decides it should mean. It's impossible to say what <<
means without knowing what a
is.
As a general convention, <<
in Ruby means "append", i.e. it appends its argument to its receiver and then returns the receiver. So, for Array
it appends the argument to the array, for String
it performs string concatenation, for Set
it adds the argument to the set, for IO
it writes to the file descriptor, and so on.
As a special case, for Fixnum
and Bignum
, it performs a bitwise left-shift of the twos-complement representation of the Integer
. This is mainly because that's what it does in C, and Ruby is influenced by C.
<<
is an operator that is syntactic sugar for calling the <<
method on the given object. On Fixnum it is defined to bitshift left, but it has different meanings depending on the class it's defined on. For example, for Array it adds (or, rather, "shovels") the object into the array.
We can see here that <<
is indeed just syntactic sugar for a method call:
[] << 1 # => [1]
[].<<(1) # => [1]
and thus in your case it just calls <<
on @unique
, which in this case is an Array
.
In Ruby, operators are just methods. Depending on the class of your variable, <<
can do different things:
# For integers it means bitwise left shift:
5 << 1 # gives 10
17 << 3 # gives 136
# arrays and strings, it means append:
"hello, " << "world" # gives "hello, world"
[1, 2, 3] << 4 # gives [1, 2, 3, 4]
It all depends on what the class defines <<
to be.
The << function, according to http://ruby-doc.org/core-1.9.3/Array.html#method-i-3C-3C, is an append function. It appends the passed-in value to the array and then returns the array itself. Ruby objects can often have functions defined on them that, in other languages, would look like an operator.
<< is just a method. It usually means "append" in some sense, but can mean anything. For strings and arrays it means append/add. For integers it's bitwise shift.
Try this:
class Foo
def << (message)
print "hello " + message
end
end
f = Foo.new
f << "john" # => hello john