Blocks
block就是用大括号或者do...end包围起来的代码块。这两种形式只有优先级有差别。一般来说,单行的block就用大括号,多行的block用do...end
Programming Ruby 写道
You can think of a block as being somewhat like the body of an anonymous method.
Block就像是匿名函数。对Block放在函数调用的后面,如果这个函数有参数, block就放在参数的后面,看起来就像是把这个block作为一个参数传递给了函数。
Block中的变量名作用范围
square = Shape.new(sides: 4) # assume Shape defined elsewhere
#
# .. lots of code
#
sum = 0
[1, 2, 3, 4].each do |value|
square = value * value
sum += square
end
puts sum
square.draw
# BOOM!
由于在Ruby中没有变量的声明,所以square在block中使用时,会被当作是在block外部使用过的那个square。因此square=value*value会改变square的值,从而引起错误。
为了防止在block中想要使用这个代码块的局部变量时却使用了代码块外部的变量的情况,Ruby1.9提供了两种机制
1.
value = "some shape"
[ 1, 2 ].each {|value| puts value }
puts value
produces:
1
2
some shape
Parameters to a block are now always local to a block, even if they have the same name as locals in the surrounding scope.
即:块中的参数始终被认为是块的本地变量,即使它和这个块的外部域的本地变量重名。
那么,除了参数以外如何定义在块中使用的本地变量呢?
square = "some shape"
sum = 0
[1, 2, 3, 4].each do |value; square|
square = value * value
# this is a different variable
sum += square
end
puts sum
puts square
produces:
30
some shape