三里屯摇滚 发表于 2011-11-01 22:03

主题:关于proc中包含break的问题

主题:关于proc中包含break的问题

通常代码块中如果包含break,在遇到break后,程序会返回到迭代器,然后返回到迭代器之外;而proc类似于代码块,也应该遵照这个规则,但是为什么我实验了一下却不行呢?



Ruby代码
def test1   
    3.times {|x| p x; break}      
    p "end of test1"   # 顺利执行   
end

test1   

def test2   
    p2 = Proc.new {|x| p x; break;}   
      
    p "before calling p2"
      
    3.times &p2   
      
    puts "after calling p2"    # 不能执行,且抛出LocalJumpError   
      
end

test2

def test1
        3.times {|x| p x; break}       
        p "end of test1"   # 顺利执行       
end

test1

def test2
        p2 = Proc.new {|x| p x; break;}
       
        p "before calling p2"
       
        3.times &p2
       
        puts "after calling p2"    # 不能执行,且抛出LocalJumpError
       
end

test2



test2的最后一行表达式在Ruby1.9.1中不执行且抛出LocalJumpError,而在Jruby1.6.4(按照Ruby1.9通用)中,则不执行也不报错;

幽鬼-yg 发表于 2011-11-02 23:01

谢谢 楼主
页: [1]
查看完整版本: 主题:关于proc中包含break的问题