Collecting keyword arguments in Ruby

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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:


keyword arguments


**kargs


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.


kargs


foo




1 Answer
1



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). The third parameter, and any remaining--up until the first keyword argument, go into args, and then any keyword args go to kargs


j


kargs


k


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:





Thank you, I will have a look. I though that would only happen if I called by foo(a: 7, b: 8). Perhaps that is a Ruby way to avoid an error when you call?
– rellampec
Aug 6 at 1:08



foo(a: 7, b: 8)





is there a way to avoid that to happen? I am trying to build a curry function that includes both: *args and **kw_args. Please, see this answer
– rellampec
Aug 6 at 1:21



curry


*args


**kw_args






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard