next与if是否在.each循环中? [英] next versus if in a .each loop?

查看:88
本文介绍了next与if是否在.each循环中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Ruby处理文本。基本上,我必须实现一个简单的状态机(后面有一个字符)。

I have a text processing thing I'm doing in Ruby. Basically, I have to implement a simple state machine (with one character look-behind).

此刻我的代码如下:

text.each{ |c|
  ...
  ...
  ...
  ...
  if @state!=:some_state
    next
  end
  #processing stuff for if in :some_state mode
  ...
  ...
  ...
  ...
  ...
}

这合适吗?还是应该像这样实现它:

Is this proper? Or should it rather be implemented like:

text.each{ |c|
  ...
  ...
  ...
  ...
  if @state==:some_state
    #processing stuff for if in :some_state mode
    ...
    ...
    ...
    ...
    ...
  end
}

是正确的方法还是仅仅是偏爱?哪一个与做事的红宝石方式融合在一起?

Is there a right way or is it just preference? Which one blends more with "the ruby way" of doing things?

推荐答案

完全同意@DigitalRoss,我已经看到人们使用 next 如果在评估某些条件后有一段复杂的代码,即

Totally agree with @DigitalRoss and I have seen people using next if there is complicated piece of code after some condition is being evaluated i.e.

 next if @state!=:some_state
 # some long complicated code

另一方面,如果需要根据某种条件执行简单的操作,那么我宁愿

on the other hand if there is a simple operation that needs to be performed on the basis of some condition then I would prefer

 if @state == :some_state
   #call_a_method_to_do_something
 end

 OR

 call_a_method if @state == :some_state

话虽如此,编写冗长而复杂的代码是一种不好的做法。如果您的代码干净且设计良好,那么您就不必在代码中使用 next

Having said that, its bad practice to write long complicated code. If your code is clean and well designed then you would never have to use next within your code.

这篇关于next与if是否在.each循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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