Skip to content Skip to sidebar Skip to footer

Rewriting JavaScript Break-to-label In Ruby

I'm porting a JavaScript library to Ruby, and have come across the following insanity (heavily abbreviated): function foo(){ if (foo) ... loop: while(go()){ if (...)

Solution 1:

There are multiple techniques that will work for this.

  1. I'm sure this has already occurred to you, but for the record, you could extract methods from the nightmare function until its structure looks more reasonable.

  2. You could define the outer loops with lambda and then immediately call them on the next line. This will allow you to use the return statement as a multi-level break and the closure that is created will allow you to still access the outer scope variables.

  3. You could raise an exception and rescue it.

  4. (Added by Phrogz) As suggested in the answer linked by @jleedev, you can use throw/catch, e.g.

    catch(:loop) do
      case ...
        when a
          throw :loop
        when b, c
          throw :loop if ...
        ...
      end
    end
    

Post a Comment for "Rewriting JavaScript Break-to-label In Ruby"