出口

2012-10-13 65 views
1

可能重複:
How to break outer cycle in Ruby?出口

說我有這樣的代碼:

class A 

    def initialize 
    myMethod() 
    print "This should not be printed" 
    end 

    def myMethod 
    #here 
    end 

end 

obj = A.new 
print "This should be printed" 

是否有任何命令,我可以而不是「#here」,它會退出'obj'對象並繼續下一個語句? (打印「這應該是印刷」)

+0

可能重複[如何突破外循環紅寶石?](http://stackoverflow.com/questions/ 1352120 /如何打破外部循環在紅寶石),http://stackoverflow.com/questions/4988045 – sawa

回答

3

投擲/捕獲會做到這一點:

class A 

    def initialize 
    catch :init_done do 
     myMethod() 
     print "This should not be printed" 
    end 
    end 

    def myMethod 
    throw :init_done 
    end 

end 

obj = A.new 
print "This should be printed" 
+0

這並不是完全我所希望的,但我已經做了一點研究自己和它看起來好像沒有更好的辦法,所以謝謝你的答案。 –