如何将多个参数作为数组传递给 ruby 方法? [英] How do I pass multiple arguments to a ruby method as an array?
本文介绍了如何将多个参数作为数组传递给 ruby 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这样的 rails 帮助文件中有一个方法
I have a method in a rails helper file like this
def table_for(collection, *args)
options = args.extract_options!
...
end
我希望能够像这样调用这个方法
and I want to be able to call this method like this
args = [:name, :description, :start_date, :end_date]
table_for(@things, args)
这样我就可以根据表单提交动态传入参数.方法不能重写,因为我用的地方太多了,不然怎么办?
so that I can dynamically pass in the arguments based on a form commit. I can't rewrite the method, because I use it in too many places, how else can I do this?
推荐答案
Ruby 可以很好地处理多个参数.
Ruby handles multiple arguments well.
这是一个很好的例子.
def table_for(collection, *args)
p collection: collection, args: args
end
table_for("one")
#=> {:collection=>"one", :args=>[]}
table_for("one", "two")
#=> {:collection=>"one", :args=>["two"]}
table_for "one", "two", "three"
#=> {:collection=>"one", :args=>["two", "three"]}
table_for("one", "two", "three")
#=> {:collection=>"one", :args=>["two", "three"]}
table_for("one", ["two", "three"])
#=> {:collection=>"one", :args=>[["two", "three"]]}
(从 irb 剪切和粘贴的输出)
(Output cut and pasted from irb)
这篇关于如何将多个参数作为数组传递给 ruby 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文