我如何传递多个参数红宝石方法作为一个数组? [英] How do I pass multiple arguments to a ruby method as an array?
本文介绍了我如何传递多个参数红宝石方法作为一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这样的轨道帮助文件的方法
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 handles multiple arguments well.
<一个href=\"http://www.misuse.org/science/2008/01/30/passing-multiple-arguments-in-ruby-is-your-friend/\">Here是一个 pretty很好的例子。
Here is a pretty good example.
def table_for(collection, *args)
"Got #{collection} and #{args.join(', ')}"
end
table_for("one") » "Got one and "
table_for("one", "two") » "Got one and two"
table_for "one", "two", "three" » "Got one and two, three"
table_for("one", "two", "three") » "Got one and two, three"
table_for("one", ["two", "three"]) » "Got one and two, three"
(输出剪切和粘贴IRB)
(Output cut and pasted from irb)
这篇关于我如何传递多个参数红宝石方法作为一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文