[英]How do I pass multiple arguments to a ruby method as an array?
我有一个像这样的rails helper文件中的方法
def table_for(collection, *args)
options = args.extract_options!
...
end
我希望能够像这样调用这个方法
args = [:name, :description, :start_date, :end_date]
table_for(@things, args)
这样我就可以根据表单提交动态传入参数。 我无法重写该方法,因为我在太多地方使用它,我怎么能这样做?
Ruby很好地处理多个参数。
这是一个很好的例子。
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输出切割和粘贴)
只需这样称呼它:
table_for(@things, *args)
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.