[英]Ruby keyword arguments
I have the class. 我上课了。 Method bar should accept argument foo with default value equal to @foo 方法栏应该接受参数foo,其默认值等于@foo
class Foo
attr_accessor :foo
def bar(foo: foo)
p foo
end
end
In irb I execute: 在irb我执行:
> f = Foo.new
> f.foo = 'foobar'
> f.bar
For ruby 2.0 result is: 对于ruby 2.0,结果是:
=> "foobar"
and for ruby 2.1: 而对于红宝石2.1:
=> nil
Who can explain this behavior? 谁能解释这种行为?
Further research: 进一步的研究:
# (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"
It seems Ruby 2.1.0 "initializes" local variable before evaluating the "right side" of this statement, so foo
on the right side is treated as local variable and thus is evaluated to nil
. 在评估此语句的“右侧”之前,似乎Ruby 2.1.0“初始化”局部变量,因此右侧的foo
被视为局部变量,因此被评估为nil
。
This experiment seems to confirm my hypothesis: 这个实验似乎证实了我的假设:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.