rubyattr-accessor

Clarification on Ruby class method


I found this class from Eloquent Ruby book.

class TextCompressor
  attr_reader :unique, :index
  def initialize( text )
    @unique = []
    @index = []
    words = text.split
    words.each do |word|
      i = @unique.index( word )
      if i
        @index << i
      else
        @unique << word
        @index << unique.size - 1
      end
    end 
  end
end

It works like this:

text = "This specification is the spec for a specification"
compressor = TextCompressor.new(text)
compressor.unique #=> ["This", "specification", "is", "the", "spec", "for", "a"]
compressor.index #=> [0, 1, 2, 3, 4, 5, 6, 1]
  1. What is unique in @index << unique.size - 1, and where did it get its value from?
  2. Are compressor.unique and compressor.index coming from attr_reader :unique, :index, or @unique and @index?

Solution

    1. In the context of the initialize method the unique is the same as self.unique and the self here is the instantiated object (TextCompressor.new)

    self.unique in this case will return you the value of @unique variable

    1. The reason you can call compressor.unique and compressor.index is coming from attr_reader :unique, :index. This line sets getters for you (getter is a method to query object for instance variable value).