【发布时间】:2016-05-18 05:32:22
【问题描述】:
为什么最后一行的结果是 nil 而不是 15?
class TextC
attr_accessor :thing1
def initialize
thing1 = 15
puts "thing: #{thing1}"
some_method
end
def some_method
puts "ho there, wanderer"
end
end
tc = TextC.new
# thing: 15
# ho there, wanderer
# => #<TextC:0x007fe5617f1b30>
tc.thing1
# => nil
我们已经确定 Ruby 将 thing1=value 视为局部变量的设置,但为什么呢?
为什么访问器方法没有被推断为我正在尝试做的事情,但是 some_method 呢? attr_accessor 结果是否仅在初始化后计算?
【问题讨论】:
-
它把它当作本地人。
-
谁提议关闭这个问题?这很愚蠢。
标签: ruby