2010-01-10 118 views
4

我对ruby非常陌生,我试图用rails框架编写一个web应用程序。通过阅读,我看到了这样的方法:Ruby多个命名参数

some_method "first argument", :other_arg => "value1", :other_arg2 => "value2" 

你可以传递无限数量的参数。

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

感谢您的帮助。

回答

17

如果您以这种方式调用该方法,则Ruby会采用值为Hash的方法,因此可行。

这里是你如何定义一个:

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

而且你可以这样调用它:

my_method('nice', {:first => true, :second => false}) 

或者

my_method('nice', :first => true, :second => false) 
1

也许这* ARGS可以帮助您?

def meh(a, *args) 
puts a 
args.each {|x| y x} 
end 

结果这种方法是

irb(main):005:0> meh(1,2,3,4) 
1 
--- 2 
--- 3 
--- 4 
=> [2, 3, 4] 

但我更喜欢在我的脚本this method

0

可以使最后一个参数是一个可选的哈希以实现:

def some_method(x, options = {}) 
    # access options[:other_arg], etc. 
end 

然而,在红宝石2.0.0,一般最好使用一个新的功能,称为keyword arguments

def some_method(x, other_arg: "value1", other_arg2: "value2") 
    # access other_arg, etc. 
end 

使用新的语法,而不是使用哈希的优点是:

  • 这是打字不太访问可选参数(例如other_arg而不是options[:other_arg])。
  • 指定可选参数的默认值很容易。
  • Ruby会自动检测调用者是否使用了无效的参数名称并引发异常。

新语法的一个缺点是你不能(就我所知)将所有关键字参数发送给其他方法,因为你没有代表它们的哈希对象。

谢天谢地,调用这两种类型的方法的语法是相同的,所以您可以在不破坏良好的代码的情况下从一个更改为另一个。