Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access an instance variable without using the @ sign

Tags:

ruby

Here is an example from a book:

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| 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( word )
    @unique << word
    unique.size - 1
  end
end

In the method add_unique_word the author access the variable unique without using the @ sign (unique.size - 1). How is it possible, and why it is so?

like image 436
Kostya Avatar asked Mar 19 '13 20:03

Kostya


2 Answers

This line attr_reader :unique, :index created a getter for the attribute:

def unique
 @unique
end

what you see in the line unique.size - 1 is a method call to the getter, then accesing the size property of it.

like image 169
fmendez Avatar answered Sep 20 '22 15:09

fmendez


The attr_reader :unique call adds an accessor making @unique publicly available at unique. It's a strange choice that the author made to mix and match using both @unique and unique though.

like image 40
Dan Wich Avatar answered Sep 19 '22 15:09

Dan Wich