简体   繁体   English

在Ruby中删除额外的关键字参数

[英]Skipping extra keyword arguments in Ruby

I defined a method: 我定义了一个方法:

def method(one: 1, two: 2)
   [one, two]
end

and when I call it like this: 当我这样称呼时:

method one: 'one', three: 'three'

I get: 我明白了:

ArgumentError: unknown keyword: three

I do not want to extract desired keys from a hash one by one or exclude extra keys. 我不想逐个从散列中提取所需的键或排除额外的键。 Is there way to circumvent this behaviour except defining the method like this: 有没有办法绕过这种行为,除了定义这样的方法:

def method(one: 1, two: 2, **other)
  [one, two, other]
end

If you don't want to write the other as in **other , you can omit it. 如果你不想写other作为**other ,你可以忽略它。

def method(one: 1, two: 2, **)
  [one, two]
end

Not sure if it works in ruby 2.0, but you can try using **_ to ignore the other arguments. 不确定它是否在ruby 2.0中有效,但您可以尝试使用**_忽略其他参数。

def method(one: 1, two: 2, **_)

In terms of memory usage and everything else, I believe there's no difference between this and **other , but underscore is a standard way to mute an argument in ruby. 在内存使用和其他一切方面,我相信这与**other没有区别,但下划线是在ruby中静音参数的标准方法。

A common way to approach this is with an options hash. 解决此问题的常用方法是使用选项哈希。 You will see this, frequently: 你会经常看到这个:

def method_name(opts={})
  one = opts[:one] || 1  # if caller doesn't send :one, provide a default
  two = opts[:two] || 2  # if caller doesn't send :two, provide a default

  # etc
end

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

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