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

由网友(傲气与我同生)分享简介:我可以定义这样的方法:I am able to define a method like this:def test(id, *ary, hash_params)# Do stuff hereend但这使得 hash_params 参数是强制性的.这些也不起作用:But this makes the hash_...

我可以定义这样的方法:

I am able to define a method like this:

def test(id, *ary, hash_params)
  # Do stuff here
end

但这使得 hash_params 参数是强制性的.这些也不起作用:

But this makes the hash_params argument mandatory. These don't work either:

def t(id, *ary, hash_params=nil)  # SyntaxError: unexpected '=', expecting ')'
def t(id, *ary, hash_params={})   # SyntaxError: unexpected '=', expecting ')'

有没有办法让它成为可选的?

Is there a way to make it optional?

推荐答案

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

You can't do that. You have to think about how Ruby would be able to determine what belongs to *ary and what belongs to the optional hash. Since Ruby can't read your mind, the above argument combination (splat + optional) is impossible for it to solve logically.

你要么必须重新排列你的论点:

You either have to rearrange your arguments:

def test(id, h, *a)

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

In which case h will not be optional. Or then program it manually:

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.
阅读全文

相关推荐

最新文章