处理 3 个或更多默认参数 Ruby

Dealing with 3 or more default arguments Ruby

我见过一些在创建方法时传递默认参数的示例,但是如果您只想替换第一个和第三个参数,其中 none 似乎可以解决问题...这是一个示例

def foo(a = 1, b = 2, c = 3)
    puts [a, b, c]
end

foo(1, 2) 
#=> [1, 2, 3]

当我尝试分配 a=5 和 c=7 并保持 b 的默认值时,如下所示:

foo(a=5,c=7) 

我明白了

=> 5,7,3

但我预计 5,2,7

完成此任务的正确方法是什么?

使用关键字参数?

def foo(a: 1, b: 2, c: 3)
  puts [a, b, c]
end

foo(a: 5, c: 7) 

I've seen a few examples of passing default arguments when creating methods, but none of them seem to address if you want to substitute only the first and third argument...

那是因为不可能。

默认参数从左到右绑定。我在回答这些问题时写了更多关于参数如何绑定到参数的内容:

  • Mixing keyword with regular arguments in Ruby?
  • Why can I have required parameters after a splat in Ruby but not optional ones?