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?
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.
In ruby '<<' operator is basically used for: Appending a value in the array (at last position) [2, 4, 6] << 8 It will give [2, 4, 6, 8] It also used for some active record operations in ruby.
The === (case equality) operator in Ruby.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With