如何同时使用 splat 和可选哈希在 ruby​​ 中定义方法? [英] How to define a method in ruby using splat and an optional hash at the same time?

查看:30
本文介绍了如何同时使用 splat 和可选哈希在 ruby​​ 中定义方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以定义这样的方法:

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.

这篇关于如何同时使用 splat 和可选哈希在 ruby​​ 中定义方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆