[英]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.