Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification on the Ruby << Operator

Tags:

oop

ruby

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 give 15 which is 1111 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?

like image 858
yretuta Avatar asked Mar 16 '12 00:03

yretuta


People also ask

What is the << operator in Ruby?

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.

What does << mean in Ruby class?

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.

What does === mean in Ruby?

The === (case equality) operator in Ruby.


1 Answers

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.

like image 93
Jörg W Mittag Avatar answered Sep 27 '22 20:09

Jörg W Mittag