Progmming Ruby学习 第四章 之 Blocks

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值