【发布时间】:2011-01-03 13:26:21
【问题描述】:
我对 ruby 很陌生,我正在尝试使用 rails 框架编写一个 Web 应用程序。通过阅读,我看到方法被这样调用:
some_method "first argument", :other_arg => "value1", :other_arg2 => "value2"
您可以传递无限数量的参数。
如何在 ruby 中创建一个可以以这种方式使用的方法?
感谢您的帮助。
【问题讨论】:
我对 ruby 很陌生,我正在尝试使用 rails 框架编写一个 Web 应用程序。通过阅读,我看到方法被这样调用:
some_method "first argument", :other_arg => "value1", :other_arg2 => "value2"
您可以传递无限数量的参数。
如何在 ruby 中创建一个可以以这种方式使用的方法?
感谢您的帮助。
【问题讨论】:
您可以将最后一个参数设为可选哈希来实现:
def some_method(x, options = {})
# access options[:other_arg], etc.
end
但是,在 Ruby 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])。新语法的一个缺点是您不能(据我所知)轻松地将所有关键字参数发送到其他方法,因为您没有代表它们的哈希对象。
谢天谢地,调用这两种方法的语法是相同的,因此您可以在不破坏良好代码的情况下从一种方法更改为另一种方法。
【讨论】:
也许 *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 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
【讨论】:
这是可行的,因为如果您以这种方式调用该方法,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 )
【讨论】: