在一个采用多个可选参数的方法中,如何指定除第一个之外的任何参数?

Sco*_*ler 9 ruby

我有这样的方法:

def foo(fruit='apple', cut="sliced", topping="ice cream")
  # some logic here
end
Run Code Online (Sandbox Code Playgroud)

如何调用它只覆盖顶部参数但使用其他参数的默认值,如下所示

foo('','','hot fudge')
Run Code Online (Sandbox Code Playgroud)

当然这不能按预期工作,但我想只为第三个可选参数提供一个值,并让前两个参数保持默认值.我知道如何用哈希做这个,但是使用上面的语法是他们的一种快捷方式吗?

she*_*onh 24

从Ruby 2.0开始,您可以使用关键字参数:

def foo(fruit: 'apple', cut: "sliced", topping: "ice cream")
  [fruit, cut, topping]
end

foo(topping: 'hot fudge') # => ['apple', 'sliced', 'hot fudge']
Run Code Online (Sandbox Code Playgroud)

  • 从Ruby 2.1开始,支持“强制关键字参数”,请参见[发行说明](https://github.com/ruby/ruby/blob/ruby_2_1/NEWS#L16-17) (3认同)

ram*_*ion 18

您无法使用此语法在ruby中执行此操作.我会为此推荐哈希语法.

def foo(args={})
  args[:fruit]    ||= 'apple'
  args[:cut]      ||= 'sliced'
  args[:topping]  ||= 'ice cream'
  # some logic here
end

foo(:topping => 'hot fudge')
Run Code Online (Sandbox Code Playgroud)

您也可以使用位置参数执行此操作:

def foo(fruit=nil,cut=nil,topping=nil)
  fruit    ||= 'apple'
  cut      ||= 'sliced'
  topping  ||= 'ice cream'
  # some logic here
end

foo(nil,nil,'hot fudge')
Run Code Online (Sandbox Code Playgroud)

请记住,这两种技术都会阻止您将实际nil参数传递给函数(有时可能需要)