没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
试读
3页
Block 定义 some_array.each { |value| puts value + 3 } sum = 0 other_array.each do |value| sum += value puts value / sum end A block is somewhat like the body of an anonymous method Block can take parameters Block 只有被 method 调用时才会起作用,如果 method 中有参数,block 出现在最后面 Block 中的变量 如果 block
资源推荐
资源详情
资源评论
深入讲解深入讲解Ruby中中Block代码快的用法代码快的用法
Block
定义定义
some_array.each { |value| puts value + 3 }
sum = 0
other_array.each do |value|
sum += value
puts value / sum
end
A block is somewhat like the body of an anonymous method
Block can take parameters
Block 只有被 method 调用时才会起作用,如果 method 中有参数,block 出现在最后面
Block 中的变量中的变量
如果 block 的本地变量的名字和 block 之外但是在同样 scope 里面的 变量名字一样,那他们两个是一样的。block 内变量的值
会改变 block 外变量的值。
sum = 0
[1,2,3,4].each do |value|
sum += value
puts value / sum
end
puts sum # => 30
如果 block 中的变量只出现在 block 中,那么它只是 block 中本地变量,无法在 block 之外被引用。
sum = 0
[1,2,3,4].each do |value|
square = value * value
sum += square
end
puts sum # => 30
puts square # undefined local variable or method 'square' for main:Object <NameError>
Parameters to a block are always local to a block, even if they have the same name as locals in the surrounding scope.
value = "some shape"
[1,2].each { |value| puts value }
puts value
# 1
# 2
# some shape
You can define a block-local variables by putting them after s semicolon in the block's parameter list
square = "some shape"
sum = 0
[1,2,3,4].each do |value; square|
square = value * value
sum += square
end
puts sum # 30
puts square # some shape
By making square block-local, values assigned inside the block will not affect the value of the variable with the same name
in the outer scope.
Blocks for Transactions
You can use blocks to define a chunk of code that must be run under some kind of transnational control
class File
def self.open_and_process(*args)
f = File.open(*args)
yield f
f.close
资源评论
weixin_38689113
- 粉丝: 1
- 资源: 974
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功