-1

While a method with a default value profile can accept nil (besides a hash):

def f(options = {})
  options
end

f(hoge: "AAA", foo: "BBB") #=> {:hoge=>"AAA", :foo=>"BBB"}
f(nil) #=> nil

A method with double splat raises an error with nil:

def f(**options)
  options
end

f(hoge: "AAA", foo: "BBB") #=> {:hoge=>"AAA", :foo=>"BBB"}
f(nil) # => wrong number of arguments (1 for 0) (ArgumentError)

When should I use double splat and when should I use = {}?

JAL
  • 41,701
  • 23
  • 172
  • 300
shingo.nakanishi
  • 2,045
  • 2
  • 21
  • 55
  • I think this might be a duplicate of [What does a double * (splat) operator do](http://stackoverflow.com/questions/18289152/what-does-a-double-splat-operator-do) – Linus Oleander Nov 19 '15 at 23:54
  • [ruby - What does a double * (splat) operator do - Stack Overflow](http://stackoverflow.com/questions/18289152/what-does-a-double-splat-operator-do) not say error. – shingo.nakanishi Nov 20 '15 at 00:13
  • It explains what the `**` operator does. Passing `nil` raises an error as there are no named arguments thus giving the error *wrong number of arguments*. – Linus Oleander Nov 20 '15 at 00:16
  • [This article - Ruby and double splat operator](http://blog.simplificator.com/2015/03/20/ruby-and-the-double-splat-operator/_) explains the scenario you have mentioned - error is reported for non-hash inputs to double splat operator. It also explains the typical use of double splat. – Wand Maker Nov 20 '15 at 12:12

1 Answers1

1

If the input to the method MUST be options hash, then, use double splat operator **.

Using options = {} only declares the default value to be empty hash, however, it does not necessarily guarantee that caller will pass hash - she may pass non-hash values and nil.

If the function was implemented using double splat (**) - as evident in examples you have provided - then non-hash and nil values will not be accepted and will be reported as error.

Wand Maker
  • 18,476
  • 8
  • 53
  • 87