在Ruby中重写JavaScript的标签分解法 [英] Rewriting JavaScript break-to-label in Ruby

查看:47
本文介绍了在Ruby中重写JavaScript的标签分解法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个JavaScript库移植到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 (...) break;
      switch(...){
        case a:
          break loop;  
        case b:
        case c:
          if (...) break loop;
          ...
          break;
        case d:
          if (...) break loop;
          // fall through
        case e:
          if (...) break loop;
          ...
          break;    
        case f:
          if (...) break loop;
          object_init:
            do{
              switch(...){
                case a:
                  ...
                  break;
                case b:
                  ...
                  break object_init;        
              }
            } while(...);              
            ...
            break;
      }
    }
}

(您可以在第701-1006行上查看完整的恐怖信息。)

如何用Ruby重写?具体来说:

How would you rewrite this in Ruby? Specifically:


  • 处理混合的 break break循环

  • 处理交换机中偶发的掉线

大概是一个好的通用策略可以使我克服其他情况,例如嵌套的 object_init 也会发生。

Presumably a good general strategy for these will get me through other situations, like the nested object_init breaking that also occurs.

编辑:我多么愚蠢;这样的JavaScript失败:

Edit: How silly of me; a JavaScript "fall through" like this:

switch(xxx){
  case a:
    aaa;
  case b:
    bbb;
  break;
}

可以在Ruby中轻松重写为:

can easily be rewritten in Ruby as:

case xxx
  when a, b
    if a===xxx
      aaa
    end
    bbb
end


推荐答案


  1. 我确定这已经发生在您身上了,但可以记录一下,您可以提取方法从噩梦函数直到其结构看起来更合理。

  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.

您可以使用 lambda 定义外部循环,然后立即对其进行调用下一行。这将允许您将 return 语句用作多级 break ,并且创建的闭包将允许您仍然访问外部作用域变量。

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.

您可以提出异常并予以挽救。

You could raise an exception and rescue it.

(由Phrogz添加)按照@jleedev链接的答案中的建议,您可以使用throw / catch,例如

(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


这篇关于在Ruby中重写JavaScript的标签分解法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆