简体   繁体   English

Ruby 需要的关键字参数

[英]Ruby required keyword arguments

For Ruby methods, the required keyword syntax is nice对于 Ruby 方法,所需的关键字语法很好

def foo(bar:, baz:)
  :
end

foo(bar: true, baz: false) # OK
foo(bar: true) # missing keyword argument error

Can one 'splat' the list of required keywords with some kind of magic?可以用某种魔法“splat”所需关键字的列表吗? ie,即,

required_keywords = [:bar, :baz]
def foo(magic(required_keywords))
  :
end

I expect not, but I'm often surprised with what Ruby can be persuaded to do.我预计不会,但我经常对 Ruby 可以被说服做的事情感到惊讶。

The splat (*) and double spla t (**) operators allow a method to take an arbitrary number of arguments. splat (*) 和double spla t (**) 运算符允许方法采用任意数量的参数。 The former will store the arguments in an array and the latter will store them in a hash.前者将参数存储在一个数组中,后者将它们存储在一个散列中。

There is also the options hash , which is an optional hash parameter, usually included as the last parameter at the method declaration.还有选项 hash ,它是一个可选的散列参数,通常作为方法声明的最后一个参数包含在内。 It can also take an arbitrary number of arguments (actually, they are plain hash items).它还可以接受任意数量的参数(实际上,它们是普通的散列项)。

However, in both of the above cases, the number of arguments is unknown when you declare the method.但是,在上述两种情况下,声明方法时参数的数量是未知的。 Hence, you can't make an unknown number of arguments "required".因此,您不能将未知数量的参数设为“必需”。

More info on splat, double splat and required keyword parameters is available at this blog post .有关 splat、double splat 和所需关键字参数的更多信息,请参阅此博客文章

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

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