Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby keyword arguments

Tags:

ruby

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?

like image 544
user3309314 Avatar asked May 13 '26 09:05

user3309314


1 Answers

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"
like image 100
Marek Lipka Avatar answered May 15 '26 01:05

Marek Lipka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!