我上课了。方法栏应接受参数foo,其默认值等于@foo
class Foo
attr_accessor :foo
def bar(foo: foo)
p foo
end
end
在irb中我执行:
> f = Foo.new
> f.foo = 'foobar'
> f.bar
对于ruby 2.0,结果是:
=> "foobar"
和红宝石2.1:
=> nil
谁可以解释这种行为?
答案 0 :(得分:3)
进一步研究:
# (Ruby 2.1.0)
class Foo
attr_accessor :foo
def bar(foo: self.foo)
foo
end
end
f = Foo.new
f.foo = 'bar'
f.bar
# => "bar"
在评估此语句的“右侧”之前,似乎Ruby 2.1.0“初始化”了局部变量,因此右侧的foo
被视为局部变量,因此被评估为nil
。
这个实验似乎证实了我的假设:
class Foo
attr_accessor :foo
def bar(foo: defined?(foo))
foo
end
end
# Ruby 2.0.0:
Foo.new.bar
# => "method"
# Ruby 2.1.0:
Foo.new.bar
# => "local-variable"