【问题标题】:Break out of a conditional Statement打破条件语句
【发布时间】:2014-08-22 09:49:29
【问题描述】:

如何摆脱条件语句?在下面的例子中,有没有什么办法可以退出if语句并执行else语句,这样我就不用写两次logic1了?

不使用任何方法?

status_invoked? = true
order_present? = true

if status_invoked?
  if order_present?
    # compute logic2
  else
    # compute logic1
  end
else
  # compute logic1
end

我认为在 C 中我们有一个叫做 setJump() 的东西,它跳出 if 语句并执行 else 语句。

【问题讨论】:

  • 这里没有循环。

标签: ruby conditional-statements


【解决方案1】:

可能更简单的方法是这样的:

def compute_logic
  return unless status_invoked? #you could also throw an error here
  return compute(logic2) if order_present? 
  compute(logic1)
end

def compute(logic)
  ...
end

并在初始化时或在私有方法中定义order_present?status_invoked?,具体取决于您的需求和使用方式。

【讨论】:

    【解决方案2】:
    status_invoked? = true
    order_present? = true
    else_ecex=false
    
    if status_invoked?
      # check if order_present?
      if order_present?
       #compute logic2
         #true else part 
         else_ecex = true
      end
    end
    
    #check even else is true or false
    if(else_ecex == true)
    #Your Code 
    end
    

    【讨论】:

      【解决方案3】:

      理想情况下,您应该使用类似于 dax 的解决方案。因为该解决方案利用了良好的辅助方法。允许您根据需要操作这些辅助方法。

      但是,使用您的代码的一个可能的解决方案是根本没有 else,并在 order_present? 中使用 return?。

      status_invoked? = true
      order_present? = true
      
      if status_invoked?
        if order_present?
          # return logic2 here.
        end
      end
      # compute logic1
      

      在这个特定的示例中,您只想在 status_invoked 时执行并返回 logic2?和order_present?两者都是正确的,如果您从未到达 order_present? 中的指令,则执行 logic1?然而,即使在这个例子中,你最好创建一个辅助方法,并将 logic1 和 logic2 传递给它。

      在我个人看来,dax 的方法是更干净的方法。它读起来更清晰,而且是典型的 ruby​​ 格式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-06
        • 2017-03-31
        相关资源
        最近更新 更多