Is there goto statement in Ruby?

后端 未结 4 2045
谎友^
谎友^ 2020-12-07 00:52

Is there a way to start at a specified line, like a goto statement?

4条回答
  •  一生所求
    2020-12-07 01:18

    The goto lib is still with us :D https://rubygems.org/gems/goto/versions/0

    Conserving the entire gem for posterity:

    STACK = []
    
    class Label
      attr_accessor :name;
      attr_accessor :block;
    
      def initialize(name, block);
        @name  = name
        @block = block
      end
    
      def ==(sym)
        @name == sym
      end
    end
    
    class Goto < Exception;
      attr_accessor :label
      def initialize(label); @label = label; end
    end
    
    def label(sym, &block)
      STACK.last << Label.new(sym, block)
    end
    
    def frame_start
      STACK << []
    end
    
    def frame_end
      frame = STACK.pop
      idx   = 0
    
      begin
        for i in (idx...frame.size)
          frame[i].block.call if frame[i].block
        end
      rescue Goto => g
        idx = frame.index(g.label)
        retry
      end
    end
    
    def goto(label)
      raise Goto.new(label)
    end
    

提交回复
热议问题