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?
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.
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.
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