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 example:
a << 2
will give15
which is1111 0000
however, it does not seem to be a "Binary Left Shift Operator" in this code:
class TextCompressor
attr_reader :unique, :index
def initialize(text)
@unique = []
@index = []
add_text(text)
end
def add_text(text)
words = text.split
words.each { |word| do add_word(word) }
end
def add_word(word)
i = unique_index_of(word) || add_unique_word(word)
@index << i
end
def unique_index_of(word)
@unique.index(word)
end
def add_unique_word
@unique << word
unique.size - 1
end
end
and this question does not seem to apply in the code I have given. So with the code I have, how does the Ruby <<
operator work?
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,
means whatever
a
decides it should mean. It's impossible to say what<<
means without knowing whata
is.As a general convention,
<<
in Ruby means "append", i.e. it appends its argument to its receiver and then returns the receiver. So, forArray
it appends the argument to the array, forString
it performs string concatenation, forSet
it adds the argument to the set, forIO
it writes to the file descriptor, and so on.As a special case, for
Fixnum
andBignum
, it performs a bitwise left-shift of the twos-complement representation of theInteger
. 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. OnFixnum
it is defined to bitshift left, but it has different meanings depending on the class it's defined on. For example, forArray
it adds (or, rather, "shovels") the object into the array.We can see here that
<<
is indeed just syntactic sugar for a method call:and thus in your case it just calls
<<
on@unique
, which in this case is anArray
.<< 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:
In Ruby, operators are just methods. Depending on the class of your variable,
<<
can do different things: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.