Ruby 学习笔记 --块blocks

{} 单行的用;do...end 用
block可以带参数,也可以不带参数,参数使用||,

举例说明:
[Crabby@Crabby-Lee Book]$ irb
1.9.3-p125 :001 > sum = 0
=> 0
1.9.3-p125 :002 > (1..5).each do |v|
1.9.3-p125 :003 > name = 'smile'
1.9.3-p125 :004?> sum +=v
1.9.3-p125 :005?> end
=> 1..5
上例中name是块内的变量,离开块便不可以访问;块内可以访问块外的变量

1.9.3-p125 :016 > name = 'oooo'
1.9.3-p125 :017 > sum = 0
1.9.3-p125 :018 > (1..5).each do |v|
1.9.3-p125 :019 > name = 'inside' //如果没有显示定义块内的局部变量;name,则name将修改全局变量
1.9.3-p125 :020?> sum +=v
1.9.3-p125 :021?> end
1.9.3-p125 :022 > p sum
1.9.3-p125 :023 > p name //name 输出为inside,


Blocks
you assign a name to a block,the code in the block is always enclosed within braces({}),always invoked from a function with the same name as that of the block.This means that if you have a block with the nametest,then you use the function nametest to invoke this block.


block_name
{
statement1,
statement2
}


1.9.3-p125 :001 > def test
1.9.3-p125 :002?> puts "you r in the method"
1.9.3-p125 :003?> yield
1.9.3-p125 :004?> puts "you are again back to the method"
1.9.3-p125 :005?> yield
1.9.3-p125 :006?> end
=> nil
1.9.3-p125 :007 > test {p "Fuck"}
you r in the method
"Fuck"
you are again back to the method
"Fuck"
=> "Fuck"


有参数的调用:
def test
yield 5
puts "You are in the method test"
yield 100
end
test {|i| puts "You are in the block #{i}"}


暂时未学习,待补充.
块与方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值