#代码块是Proc 类的实例 #使用如下: def run puts "start running" yield yield puts "finish" end run{ puts "runing" } #当代码块在一行能容纳的时候 ,一般用花括号包围 i=0 run do #当代码块语句多行的时候 i += 1 puts i end #代码块也能传参数 def run2(arg) yield arg end run2 ("cai") {|name| puts "hello #{name}"} i=0 run2 2 do |x| i = i+x puts i end #代码块的运用测试 #运用代码块实现数组each 的迭代功能 puts "====== 运用代码块实现迭代 ====" class Array #给数组追加方法 for_each def for_each for i in (0...self.length) yield self[i] #循环调用代码块来进行迭代 end end end ["a","b","c"].for_each{ |i| puts i} #运用Proc 类来生成代码块 block = Proc.new{ |name| puts "hello #{name}"} def method(name,&block) block.call name end method ("cai",&block) #Proc 与 lambda def proc_test f = Proc.new{ return "jump from Proc block" } f.call return "proc_test return" #不会执行 end def lambda_test f = lambda { return "jump from lambda block" } f.call return "lambda_test return" #会执行 end puts proc_test puts lambda_test