next versus if in a .each loop?

coding-style, ruby

Solution

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

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.

Problem

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). My code at the moment looks like this: ``` 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?

Original source