我熟悉在attr_accessors
方法中使用initialize
的传统方式:
class Dog
attr_accessor :name
def initialize(name)
@name = name
end
end
dog = Dog.new("Denver")
p dog.name
=> "Denver"
我正在玩自定义writers
和readers
。我很惊讶地意识到以下几点:
reader
方法而不显式指定self
,因为self
是隐式的。 self
来调用writer
方法。 self
attr_writers
示例1 ,以便在实例方法中调用self
方法时隐式显示attr_reader
:
class Dog
def name
@name
end
def name=(val)
@name = val
end
def initialize(name)
@name = name
end
def call_name
# no need to say: p self.name
p name
end
end
dog = Dog.new("Denver")
dog.call_name
=> "Denver"
示例2 ,以便在实例方法中调用self
时显示attr_writers
不隐式。换句话说:实例变量没有设置,因为我没有在writer
之前添加self
方法:
class Dog
def name
@name
end
def name=(val)
@name = val
end
def initialize(name_val)
# works as expected with: self.name = name_val
name = name_val
end
def change_name
# works as expected with: self.name = "foo"
name = "foo"
end
end
dog = Dog.new("Denver")
p dog.name
dog.change_name
p dog.name
=> nil
=> nil
问题:调用self
时,为什么在实例方法中隐含了attr_writers
?为什么我必须在实例方法中为self
明确指定attr_writers
?
答案 0 :(得分:0)
问题:为什么
self
隐含在实例方法中attr_writers
?
因为定义局部变量优先。
所以这里:
name = "foo"
你不是写一个属性,而是定义一个局部变量name
。