views:

181

answers:

5

I've got a massive script with about 20 embedded if statements (Yay!) that is used to parse through a data file. And in a sense, that's correct because the script should not continue operating if any of those evaluations fail.

But my gut says there's a more elegant way to accomplish the same thing. I'm familiar with the statemachine plugin for rails, but that seems to be overkill (it seems to be overkill).

Any chance there's a slightly more elegant way to reduce the number of embedded 'ifs' either through a workflow, or some other way?

A: 

Just refactor the code and split parts of the conditional sections out to different functions. It will not reduce the nested if deepths but make it more readable.

Otherwise there is very little to say as it is a very generic question.

Lothar
+2  A: 

This is mostly code specific, but I can suggest 2 ways:

  1. case .. when .. then .. structure.
  2. Effectively using send or eval methods.
Swanand
+1  A: 

One approach is to construct a hash or array in which the contents are Procs that each encapsulate a given conditional. Then you can loop through the procs and test your data against each one.

JacobM
Interesting concept...then I could test any given Proc without having to go through any other ones.
btelles
+8  A: 

reverse the conditions of the if statements and leave the particular function(if you can). This way you get a lot of if's behind each other instead of nested

Toad
This is a good approach without doing anything exotic like a state machine. Another term for this technique is "guard" clauses
matt eisenberg
Perfect! Thanks Reiner!Found a link that explains the Guard clause in Ruby:http://www.thechrisoshow.com/2009/2/16/using-guard-clauses-in-your-ruby-code
btelles
no problem. glad i could help
Toad
A: 

Use haml :P

(so you dont need to end the if tags..)

Lichtamberg
or Python......
Xiong Chiamiov
Hi there. Mmmm i think you may have gotten some signals mixed. I think you may have thought that script meant "html," but it didn't. If not, then although HAML will handle embedded if statements without requiring 'end,' it's far from a full ruby parser, and after trying to put too much logic into it, I found it has many limitations.Hope this helps you with future answers!
btelles