Ruby Keyword Arguments

I have a class. The method bar should accept the foo argument with a default value of @foo

class Foo
  attr_accessor :foo

  def bar(foo: foo)
    p foo
  end
end

In irb, I do:

> f = Foo.new
> f.foo = 'foobar'
> f.bar

For ruby ​​2.0 result:

=> "foobar"

and for ruby ​​2.1:

=> nil

Who can explain this behavior?

+3
source share
1 answer

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 that Ruby 2.1.0 “initializes” the local variable before evaluating the “right side” of this operator, therefore it is fooconsidered as a local variable on the right side and therefore evaluated as 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"
+3
source

All Articles