打破条件声明

时间:2014-08-22 09:49:30

标签: ruby conditional-statements

如何退出条件声明?在下面的示例中,有没有办法退出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语句。

3 个答案:

答案 0 :(得分: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?,具体取决于您的需求及其使用方式。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

但是,使用您的代码的可能解决方案是没有elses,并在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格式。

相关问题