ruby中的 Proc、block说明

存放代码片断 
Proc可以将要执行的一些代码片断放在一起,却不立即执行,而是在后来我们想要执行它的时候来调用。 
Ruby代码   收藏代码
  1. say_hello = Proc.new { puts "Hello!" } # 代码不会立即执行  
  2.   
  3. say_hello.call # 现在我们来调用运行Proc的存放的代码  
  4. # => "Hello!"  


用Proc来组织我们的代码 
Proc是组织代码的好工具,比如现在我们要测试一下某些代码的执行花费时间,通过Proc可以很灵活地做到这一点: 
Ruby代码   收藏代码
  1. def time(a_proc)  
  2.   start = Time.now  
  3.   a_proc.call  
  4.   puts Time.now - start  
  5. end  
  6.   
  7. time(Proc.new { code_here })  
  8. time(Proc.new { more_code_here })  


Blocks! 
用Block来实现上面说的更方便,而且看起来漂亮一些: 
Ruby代码   收藏代码
  1. def time  
  2.   start = Time.now  
  3.   yield  
  4.   puts Time.now - start  
  5. end  
  6.   
  7. time { code_here }  
  8. time { more_code_here }  

那个yield就和a_proc.call类似,是作用block的一个点位符。 

向Proc和Block中传递参数 
向Proc和Block中传递参数的方式是一样的: 
Ruby代码   收藏代码
  1. def dumb_hello_world_test  
  2.   yield(5)  
  3. end  
  4.   
  5. dumb_hello_world_test {|i| puts i * 2 }  
  6. # => 10  
  7.   
  8. my_silly_proc = Proc.new {|name| puts name.upcase }  
  9. my_silly_proc.call("August Lilleaas")  
  10. # => "AUGUST LILLEAAS"  

看一下这个例子 
Ruby代码   收藏代码
  1. [1, 2, 3].map {|i| puts i * 2 }  
  2. # => 2  
  3. # => 4  
  4. # => 6  


我们自己再来实现Array中的each方法 
Ruby代码   收藏代码
  1. class Array  
  2.   def each  
  3.     i = 0  
  4.     while(i < self.length) do  
  5.       yield(self[i])  
  6.       i += 1  
  7.     end  
  8.   end  
  9. end  
  10.   
  11. my_array = ["a""b""c"]  
  12. my_array.each {|letter| puts letter }  
  13. # => "a"  
  14. # => "b"  
  15. # => "c"  


另外对于block,有两种形式 
{}和do end 前者优先级高。

转自:http://bot.iteye.com/blog/403075
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值