处理需要 的方法时已知 参数数量加上选项散列,在双拼音中捕获选项有什么区别/优势吗?
考虑
def method_a(a, **options)
puts a
puts options
end
对比
def method_b(a, options = {})
puts a
puts options
end
两者等价吗?我认为method_b更具可读性,但我仍然看到很多代码与method_a一起使用。
是否有理由在选项中使用双 splat 当常规(非选项)参数被捕获而没有 splat 时 ?
最佳答案
好吧,这取决于您所说的“已知参数数量”是什么意思,特别是对于关键字参数加上任意数量的其他关键字参数的情况,例如:
def foo(i, keyword_1: "default", **other_keywords)
end
我可以称之为
foo(6, keyword_1: "asd", other: "keyword")
和
{other: "keyword"}
将包含在 other_keywords
而 keyword_1
可以直接作为局部变量访问。没有
**
splat operator 这种行为实现起来比较麻烦,像这样:def foo(i, opts={})
keyword_1 = opts.delete(:keyword_1) || "default"
# now `opts` is the same as `other_keywords`
end
关于ruby-on-rails - Ruby 方法 Double Splat 与 Hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58162053/