2

I noticed that attempting to use the send method while passing in unpacked keyword args as a variable led to some unexpected behavior.

First the setup:

class SomeClass
  def some_method
    true
  end
end

kwargs = {}

c = SomeClass.new
c.some_method
 => true
c.some_method(**kwargs)
 => true 
c.send(:some_method, **{})
 => true

All of the above works as expected. However, if I attempt to use send in conjunction with passing key word args via a variable (as oppose to a literal), I suddenly get a 'wrong number of arguments' error

c.send(:some_method, **kwargs)
Traceback (most recent call last):
    5: from /Users/rs/.rvm/rubies/ruby-2.6.7/bin/irb:23:in `<main>'
    4: from /Users/rs/.rvm/rubies/ruby-2.6.7/bin/irb:23:in `load'
    3: from /Users/rs/.rvm/rubies/ruby-2.6.7/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
    2: from (irb):9
    1: from (irb):2:in `some_method'
ArgumentError (wrong number of arguments (given 1, expected 0))

Is this intended behavior?

Raphi
  • 410
  • 4
  • 17
  • 3
    Keyword argument handling was [changed](https://github.com/ruby/ruby/blob/4643bf5d55af6f79266dd67b69bb6eb4ff82029a/doc/NEWS-2.7.0#the-spec-of-keyword-arguments-is-changed-towards-30-) in Ruby 2.7; I believe you are seeing one of the reasons why. I tried your code on 2.7 and 3.0, and I cannot reproduce your error. (I don't have 2.6 installed, so I did not verify if I get it there, but I'll trust you that I would.) See the paragraph "Passing an empty keyword splat to a method that does not accept keywords [...]": `h = {}; def foo(*a) a end; foo(**h)` evaluates differently on 2.6 vs 2.7. – Amadan Mar 23 '22 at 03:44

0 Answers0