2

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?

rafaels88
  • 839
  • 1
  • 6
  • 19

1 Answers1

1

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]

mikdiet
  • 9,859
  • 8
  • 59
  • 68
  • I updated my question. I forgot to put the implementation of the method. Could you try again but without receiving any parameters in `foo`? – rafaels88 Mar 15 '17 at 17:40
  • 1
    I understand you had no parameters in your method. In my answer I shown why you received `ArgumentError Exception` - because double splat on variable passes empty hash as first argument into the method. @rafaels88 – mikdiet Mar 16 '17 at 07:51
  • Yes, you are right... I made some tests right now following you line of thinking, and if you pass `foo(**{a: 1})` and then `h = {a: 1}; foo(**h)`, the behavior is different than passing empty hash as you passed in your example. It seems like a bug. Thank you very much for the diagnosis! – rafaels88 Mar 16 '17 at 13:31