这里发生的只是form_for
方法在同一个调用中被参数和块调用。
下面是同时服用的参数和一个块的方法的一个基本的例子,来说明原理:
def hello(name)
puts "Hello, #{name}!"
yield if block_given?
puts "Goodbye, #{name}!"
end
该方法可以用一个单一的参数来调用,或者与一个参数和一个块:
> hello("John")
Hello, John!
Goodbye, John!
> hello("John") do
* puts "Inside the block"
* end
Hello, John!
Inside the block
Goodbye, John!
关于在您的评论的问题:
为什么有圆括号周围只有日第一个参数?在form_for后遇到open + closed括号后,Ruby如何知道在调用方法之前它应该“等待”?
如果我理解你的问题正确,你问为什么只有在form_for
调用的括号@post
,而不是整个块左右。这是在Ruby中将块传递给方法的语法 - 如果块紧跟在方法及其常规参数之后,块将与参数一起传递给方法。
这里有几个叫Ruby中的方法的最常见方式:
# Calling a method without a block
mymethod(param1, param2)
# Same as above, but leaving out parentheses
mymethod param1, param2
# Calling a method with a block that takes no arguments
# (this works without parentheses too)
mymethod(param1, param2) { do_stuff_in_block() }
# or
# (this works without parentheses too)
mymethod(param1, param2) do
do_stuff_in_block()
end
# Calling a method with a block that takes arguments
# (this works without parentheses too)
mymethod(param1, param2) do |arg1, arg2|
do_stuff_in_block(arg1, arg2)
end
# or
# (this works without parentheses too)
mymethod(param1, param2) { |arg1, arg2| do_stuff_in_block(arg1, arg2) }
看一看Blocks and Iterators in Programming Ruby如需详细了解双方如何调用与块,以及如何的方法来写你自己的方法接受块。
没有什么是铁轨中的巫毒。擦拭你的眼镜,你会看到它的全部只是红宝石! – Chirantan 2010-12-08 08:26:24
也许这会有助于查看源代码:https://github.com/rails/rails/blob/master/actionpack/lib/action_view/helpers/form_helper.rb以查看最终参数是&proc,并且是需要: `def form_for(record,options = {},&proc)raise ArgumentError,“Missing block”unless block_given?` – 2010-12-08 08:42:25
每个人都给出了令人敬畏的答案!谢谢,并为所有人+1。 谢谢杰德!我会看看这个。 – ClosureCowboy 2010-12-08 08:43:47