I have the class. Method bar should accept argument foo with default value equal to @foo
class Foo
attr_accessor :foo
def bar(foo: foo)
p foo
end
end
In irb I execute:
> f = Foo.new
> f.foo = 'foobar'
> f.bar
For ruby 2.0 result is:
=> "foobar"
and for ruby 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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With