繁体   English   中英

Ruby 方法双溅与 Hash

[英]Ruby Method Double Splat vs Hash

在处理采用已知数量的 arguments 和选项 hash 的方法时,在双 splat 中捕获选项是否有任何区别/优势?

考虑

def method_a(a, **options)
    puts a
    puts options
end

对比

def method_b(a, options = {})
   puts a
   puts options
end

两者是等价的吗? 我认为 method_b 更具可读性,但我仍然看到很多代码与 method_a 一起使用。 当常规(非选项) arguments 在没有 splat 的情况下被捕获时,是否有理由使用 double splat 作为选项?

好吧,这取决于您所说的“已知参数数量”是什么意思,特别是当您有关键字 arguments加上任意数量的其他关键字 args时,例如:

def foo(i, keyword_1: "default", **other_keywords)
end

我可以称之为

foo(6, keyword_1: "asd", other: "keyword")

并且{other: "keyword"}将包含在other_keywords中,而keyword_1可以作为局部变量直接访问。

如果没有** splat 运算符,这种行为实现起来会更加麻烦,如下所示:

def foo(i, opts={})
 keyword_1 = opts.delete(:keyword_1) || "default"
 # now `opts` is the same as `other_keywords`
end

另一个区别是**版本捕获 rest 关键字 arguments。 关键字 arguments 由符号表示,导致以下行为:

def a(**options)
  options
end

def b(options = {})
  options
end
a(a: 1) #=> {:a=>1}
a('a' => 1) #=> ArgumentError (wrong number of arguments (given 1, expected 0))

b(a: 1) #=> {:a=>1}
b('a' => 1) #=> {"a"=>1}
def c(hash_options = {}, **keyword_options)
  [hash_options, keyword_options]
end
# symbols are extracted and used as rest keyword arguments
c('a' => 1, b: 2, 'c' => 3, d: 4) #=> [{"a"=>1, "c"=>3}, {:b=>2, :d=>4}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM