我在rails助手文件中有一个方法,如下所示
def table_for(collection, *args)
options = args.extract_options!
...
end
我希望能够像这样调用这个方法
args = [:name, :description, :start_date, :end_date]
table_for(@things, args)
这样我就可以根据表单提交动态地传递参数。我不能重写这个方法,因为我在太多的地方使用它,否则我还能怎么做呢?
发布于 2009-05-06 19:23:16
Ruby很好地处理了多个参数。
Here is是一个很好的例子。
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剪切和粘贴的输出)
发布于 2009-05-06 19:11:48
就这么叫吧:
table_for(@things, *args)
splat
(*
)操作符将完成这项工作,而不必修改方法。
发布于 2015-06-18 17:30:01
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
https://stackoverflow.com/questions/831077
复制相似问题