我可以将参数传递给这样的函数:
func 1, 2, 3
Run Code Online (Sandbox Code Playgroud)
或者我可以使用括号:
func(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
后来我了解了list.each我传递的函数(不确定这是不是真的发生了)一个块来操作每个元素:
list.each {|x| puts x}
Run Code Online (Sandbox Code Playgroud)
我假设这只是作为each函数的参数传递了块,但似乎并非如此,因为:
list.each( {|x| puts x} )
Run Code Online (Sandbox Code Playgroud)
不起作用.
显示时我意识到了这一点:
5.upto(9) {|x| puts x}
Run Code Online (Sandbox Code Playgroud)
如果块只是一个参数,那么根本没有意义.
这里发生了什么?您可以指点我的任何资源来帮助解释这个问题,也许还有其他一些不明显的结构问题?
块确实有点特殊,但也可以用作参数.考虑这个功能:
def greet
yield "Hello"
end
greet{ |greeting| puts "#{greeting} to you" }
Run Code Online (Sandbox Code Playgroud)
你也可以像这样编写完全相同的东西:
def greet(&block)
block.call("Hello")
end
greet{ |greeting| puts "#{greeting} to you" }
# which is equivalent to:
my_proc = proc{ |greeting| puts "#{greeting}, nice to see you." }
greet(&my_proc)
Run Code Online (Sandbox Code Playgroud)
最后,块是一种特殊的proc形式,具有特殊的语法,使它们更有用.但你仍然可以访问过程并传递它们.