我对ruby非常陌生,我试图用rails框架编写一个web应用程序。通过阅读,我看到了这样的方法:Ruby多个命名参数
some_method "first argument", :other_arg => "value1", :other_arg2 => "value2"
你可以传递无限数量的参数。
你如何在Ruby中创建一个方法,可以以这种方式使用的?
感谢您的帮助。
我对ruby非常陌生,我试图用rails框架编写一个web应用程序。通过阅读,我看到了这样的方法:Ruby多个命名参数
some_method "first argument", :other_arg => "value1", :other_arg2 => "value2"
你可以传递无限数量的参数。
你如何在Ruby中创建一个方法,可以以这种方式使用的?
感谢您的帮助。
如果您以这种方式调用该方法,则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)
这其实只是有一个方法散列作为参数,下面是一个代码示例。
def funcUsingHash(input)
input.each { |k,v|
puts "%s=%s" % [k, v]
}
end
funcUsingHash :a => 1, :b => 2, :c => 3
详细了解这里的哈希http://www-users.math.umd.edu/~dcarrera/ruby/0.3/chp_03/hashes.html
也许这* 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。
可以使最后一个参数是一个可选的哈希以实现:
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]
)。新语法的一个缺点是你不能(就我所知)将所有关键字参数发送给其他方法,因为你没有代表它们的哈希对象。
谢天谢地,调用这两种类型的方法的语法是相同的,所以您可以在不破坏良好的代码的情况下从一个更改为另一个。