如何使用splat和可选的哈希同时在ruby中定义方法?

and*_*vom 10 ruby methods hash arguments splat

我能够定义这样的方法:

def test(id, *ary, hash_params)
  # Do stuff here
end
Run Code Online (Sandbox Code Playgroud)

但这使得hash_params论证成为强制性的.这些也不起作用:

def t(id, *ary, hash_params=nil)  # SyntaxError: unexpected '=', expecting ')'
def t(id, *ary, hash_params={})   # SyntaxError: unexpected '=', expecting ')'
Run Code Online (Sandbox Code Playgroud)

有没有办法让它可选?

Clu*_*ter 13

通过使用数组扩展,ActiveSupport支持此功能extract_options!.

def test(*args)
  opts = args.extract_options!
end
Run Code Online (Sandbox Code Playgroud)

如果最后一个元素是一个哈希,那么它将从数组中弹出它并返回它,否则它将返回一个空哈希,这在技术上与你想要(*args, opts={})做的相同.

ActiveSupport数组#extract_options!


Cas*_*per 11

你不能这样做.您必须考虑Ruby如何能够确定属于 *ary哪个以及什么属于可选哈希.由于Ruby无法读懂你的想法,上面的参数组合(splat + optional)是不可能在逻辑上解决的.

你要么重新安排你的论点:

def test(id, h, *a)
Run Code Online (Sandbox Code Playgroud)

在这种情况下h不会是可选的.或者手动编程:

def test(id, *a)
  h = a.last.is_a?(Hash) ? a.pop : nil
  # ^^ Or whatever rule you see as appropriate to determine if h
  # should be assigned a value or not.
Run Code Online (Sandbox Code Playgroud)