简体   繁体   English

Ruby 关键字参数说明

[英]Ruby keyword arguments clarification

Lately I saw this function signature:最近我看到了这个函数签名:

   class Foo < Bar
    def initialize(arg: {})
      ...
   end

What does the keyword argument ( arg: {} ) with the curly braces means here?带花括号的关键字参数 ( arg: {} ) 在这里意味着什么?

Its just a keyword argument with an empty hash as the default value:它只是一个关键字参数,默认值为空散列:

def initialize(arg: {})
  arg
end

irb(main):011:0> initialize().class
=> Hash

Its really strange and unidiomatic though.不过,它真的很奇怪而且很单一。 Before Ruby 2.0 introduced first-class support for keywords you declared a method that takes an optional options hash as:在 Ruby 2.0 引入对关键字的一流支持之前,您声明了一个采用可选选项散列的方法:

def initialize(hash = {})

end

This argument had to be at the end of the list of.这个参数必须在列表的末尾。 The name is not significant.这个名字并不重要。

With Ruby 2.0 you can declare a method that takes any number of keywords with a double splat:使用 Ruby 2.0,您可以声明一个方法,该方法采用任意数量的带有双拼音的关键字:

def initialize(**other_keyword_args)

end

You can combine it with positional and named keyword arguments as well:您也可以将它与位置和命名关键字参数结合使用:

def initialize(a, b = 2, foo:, bar: 2, **other_keyword_args)

end

Using initialize(arg: {}, ...) would make sense if there where more parameters and this one takes a hash but on its own its just strange.使用initialize(arg: {}, ...)是有意义的,如果有更多的参数,这个参数需要一个散列,但它本身就很奇怪。

Ruby doesn't need braces ( {} ) around a hash when passing the last argument to a method:将最后一个参数传递给方法时,Ruby 不需要将散列括起来的大括号 ( {} ):

def foo(anything)
  anything       # => {:arg=>{}}
          .class # => Hash
end

foo(arg: {})

For more information see " Calling Methods ."有关详细信息,请参阅“ 调用方法”。

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

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