'attr_reader' 是否使局部变量在整个 class 期间可用?
Does 'attr_reader' make a local variable available throughout a class?
为什么下面is_a_peacock?
方法中的type
变量可用?
class Animal
attr_reader :type
def initialize(type)
@type = type
end
def is_a_peacock?
if type == "peacock"
return true
else
return false
end
end
end
an = Animal.new('peacock')
puts an.is_a_peacock? # => true
为什么注释掉 @type
的初始化会使 type
不可用?
class Animal
attr_reader :type
def initialize(type)
#@type = type
end
def is_a_peacock?
if type == "peacock"
return true
else
return false
end
end
end
an = Animal.new('peacock')
puts an.is_a_peacock? # => false
您可以认为 attr_reader :type
是为您做的:
def type
@type
end
但它不会根据您传递给初始化程序的内容自动分配实例变量,就像您假设它会做的那样。
由于您不再执行 @type = type
,@type
保持其默认值 nil
。默认情况下,每个实例变量都是 nil。
旁注,而不是
if type == "peacock"
return true
else
return false
end
你可以只写
type == "peacock"
"Why does commenting out the initialization of @type
make type
unavailable?"
没有。方法 type
可用。只是没有初始化。因为你把它注释掉了。
如果方法 type
不可用,您的程序将会崩溃。 (就像注释掉 attr_reader
时一样)。
Why is the type
variable available in the is_a_peacock?
method in the following?
你对这个问题的假设不成立。 is_a_peacock?
方法体内的 type
不是局部变量。这是一个方法调用。
Why does commenting out the initialization of @type
make type
unavailable?
没有。方法type
可用,其中returns值为@type
,默认为nil
。
为什么下面is_a_peacock?
方法中的type
变量可用?
class Animal
attr_reader :type
def initialize(type)
@type = type
end
def is_a_peacock?
if type == "peacock"
return true
else
return false
end
end
end
an = Animal.new('peacock')
puts an.is_a_peacock? # => true
为什么注释掉 @type
的初始化会使 type
不可用?
class Animal
attr_reader :type
def initialize(type)
#@type = type
end
def is_a_peacock?
if type == "peacock"
return true
else
return false
end
end
end
an = Animal.new('peacock')
puts an.is_a_peacock? # => false
您可以认为 attr_reader :type
是为您做的:
def type
@type
end
但它不会根据您传递给初始化程序的内容自动分配实例变量,就像您假设它会做的那样。
由于您不再执行 @type = type
,@type
保持其默认值 nil
。默认情况下,每个实例变量都是 nil。
旁注,而不是
if type == "peacock"
return true
else
return false
end
你可以只写
type == "peacock"
"Why does commenting out the initialization of
@type
maketype
unavailable?"
没有。方法 type
可用。只是没有初始化。因为你把它注释掉了。
如果方法 type
不可用,您的程序将会崩溃。 (就像注释掉 attr_reader
时一样)。
Why is the
type
variable available in theis_a_peacock?
method in the following?
你对这个问题的假设不成立。 is_a_peacock?
方法体内的 type
不是局部变量。这是一个方法调用。
Why does commenting out the initialization of
@type
maketype
unavailable?
没有。方法type
可用,其中returns值为@type
,默认为nil
。