简体   繁体   English

在Ruby中收集关键字参数

[英]Collecting keyword arguments in Ruby

Just trying to understand how to collect arguments in Ruby, I came up with the following snippet, that seems to fail to collect keyword arguments in **kargs in some case: 只是想了解如何在Ruby中收集参数,我想出了以下代码段,在某些情况下,它似乎无法在**kargs中收集keyword arguments

def foo(i, j= 9, *args, k: 11, **kargs)
  puts "args: #{args}; kargs: #{kargs}"
end

foo(a: 7, b: 8)
# output: args: []; kargs: {}
foo(9, a: 7, b: 8)
# output: args: []; kargs: {:a=>7, :b=>8}
foo(9, 10, 13, a: 7, b: 8)
# output: args: [13]; kargs: {:a=>7, :b=>8}

I would like to know why it does not collect kargs in the first call to foo , while in the second call it does. 我想知道为什么它在第一次调用foo时不收集kargs ,而在第二次调用中却收集了kargs

It's because the first parameter i , is a required parameter (no default value), so, the first value passed to the method (in your first example, this is the hash {a: 7, b: 8} ) is stored into it. 这是因为第一个参数i是必需参数(没有默认值),因此,传递给方法的第一个值(在您的第一个示例中,这是哈希{a: 7, b: 8} )存储在其中。

Then, since everything else is optional, the remaining values (if any, in this example, there are none) are filled in, as applicable. 然后,由于其他所有内容都是可选的,因此将其余所有值(如果有,在此示例中为空)填充(如果适用)。 IE, the second parameter will go to j , unless it is a named parameter, then it goes to kargs (or k ). IE,第二个参数将转到j ,除非它是命名参数,否则它将转到kargs (或k )。 The third parameter, and any remaining--up until the first keyword argument, go into args , and then any keyword args go to kargs 第三个参数以及直到第一个关键字参数之前的所有剩余参数进入args ,然后所有关键字args进入kargs

def foo(i, j= 9, *args, k: 11, **kargs)
  puts "i: #{i}; args: #{args}; kargs: #{kargs}"
end

foo(a: 7, b: 8)
# i: {:a=>7, :b=>8}; args: []; kargs: {}

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

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