Ruby多个命名参数

Bri*_*asa 4 ruby methods arguments

我是ruby的新手,我正在尝试使用rails框架编写Web应用程序.通过阅读我看到的方法被调用如下:

some_method "first argument", :other_arg => "value1", :other_arg2 => "value2"
Run Code Online (Sandbox Code Playgroud)

在哪里可以传递无限数量的参数.

如何在ruby中创建一个可以这种方式使用的方法?

谢谢您的帮助.

Dou*_*ner 17

这是有效的,因为Hash如果你以这种方式调用方法,Ruby假设值是a .

以下是如何定义一个:

def my_method( value, hash = {})
  # value is requred
  # hash can really contain any number of key/value pairs
end
Run Code Online (Sandbox Code Playgroud)

你可以像这样称呼它:

my_method('nice', {:first => true, :second => false})
Run Code Online (Sandbox Code Playgroud)

要么

my_method('nice', :first => true, :second => false )
Run Code Online (Sandbox Code Playgroud)