rubysplatdouble-splat

Expanding empty hash in variable with double splat in Ruby


I got this strange behavior trying to expand the hash variable using double splat. Do not know why this is happening.

My ruby version

ruby 2.2.6p396 (2016-11-15 revision 56800)

Scenario

class MyClass
  def my_method; end
end

MyClass.new.my_method(*[]) # returns nil

MyClass.new.my_method(**{}) # returns nil

MyClass.new.my_method(*[], **{}) # returns nil


# Using variables

values = []
k_values = {}

MyClass.new.my_method(*values) # returns nil

MyClass.new.my_method(**k_values) # *** ArgumentError Exception: Wrong number of arguments. Expected 0, got 1.

MyClass.new.my_method(*values, **k_values) # *** ArgumentError Exception: Wrong number of arguments. Expected 0, got 1.


# In summary

MyClass.new.my_method(**{}) # returns nil

MyClass.new.my_method(**k_values) # *** ArgumentError Exception: Wrong number of arguments. Expected 0, got 1.

Does any one knows why this is happening? Is this a bug?


Solution

  • Yes, it very looks like a bug

    def foo(*args)
      args
    end
    
    foo(**{})
    # => []
    
    h = {}
    
    foo(**h)
    # => [{}]
    

    It passes empty hash as first argument in case of double splat of variable.

    My version is ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16]