不带@的调用实例变量 [英] Calling Instance Variables without @
问题描述
我是Ruby编程的新手,我现在看到了一些示例,在这些示例中调用实例变量时,其前面没有"@"符号.
I'm new to Ruby programming and I've seen a few examples now where an instance variable is being called without the "@" symbol in front of it.
我不确定是否是因为该类中的 attr_reader
导致了方法的调用以及实例变量是否存储在方法中,或者我是否对此有错误的理解实例变量.
I'm not sure if this because the method is being called and the instance variable is stored in the method as a result of a attr_reader
in the class or if because I have the wrong understanding of instance variables.
这是我所指的示例,摘自Russ Olsen的雄辩的Ruby,其中 @unique
数组具有调用的 size
方法,而没有"@""前面的符号:
Here's an example of what I'm referring to taken from Russ Olsen's Eloquent Ruby, where the @unique
array has the size
method called on it without the "@" symbol in front of it:
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
推荐答案
我也是Ruby的新手,已经学习了几周.我相信:
I'm also new to Ruby and have been learning for a couple weeks. I believe:
attr_reader :unique
在功能上与定义方法相同:
is functionally identical to defining the method:
def unique
@unique
end
这篇关于不带@的调用实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!