[英]How do I pass multiple arguments to a ruby method as an array?
I have a method in a rails helper file like this 我有一个像这样的rails helper文件中的方法
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. Ruby很好地处理多个参数。
Here is a pretty good example. 这是一个很好的例子。
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"]]}
(Output cut and pasted from irb) (从irb输出切割和粘贴)
Just call it this way: 只需这样称呼它:
table_for(@things, *args)
The splat
( *
) operator will do the job, without having to modify the method. splat
( *
)运算符将完成工作,而无需修改方法。
class Hello
$i=0
def read(*test)
$tmp=test.length
$tmp=$tmp-1
while($i<=$tmp)
puts "welcome #{test[$i]}"
$i=$i+1
end
end
end
p Hello.new.read('johny','vasu','shukkoor')
# => welcome johny
# => welcome vasu
# => welcome shukkoor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.