lots of code
.
.
.
if …
some lines of code
if …
some lines of code
if …
some lines of code
if …
some lines of code
if …
some lines of code
etc
This makes it difficult to see the overall logic so I want to change it
to something like:
lots of code
.
.
.
if …
call something
if …
call something
if …
call something
if …
call something
if …
call something
etc
but if I use methods I will have to pass lots of variables or use
global variables and then it gets clumsy changing everything - is there
some way of simply calling a block of code and then returning to the
same position in the nested “ifs”?
if …
some lines of code
if …
some lines of code
if …
some lines of code
if …
some lines of code
etc
This makes it difficult to see the overall logic
I can believe that.
if ..
call something
if ..
call something
if ..
call something
etc
That does not seem much better to me. Why do you need such a
structure of code? Can you be more specific about what you are doing
there? Maybe a completely different structure of the code is even
better.
but if I use methods I will have to pass lots of variables or use global
variables and then it gets clumsy changing everything - is there some way of
simply calling a block of code and then returning to the same position in
the nested “ifs”?
I don’t think there is. Unless, maybe, if you declare all local
variables at the beginning of the method, followed by a whole bunch of
Procs which you call where “something” is written. I doubt though
that this will be more readable.
Wouldn’t a case statement work for this kind of thing?
case statements are more of an if…else replacement rather than nested
ifs. If you can refactor the code to use case statements then that’s a
good start because from there you can replace the branches with calls to
objects.
Nested ifs are really hard to get rid of without major code refactoring.
lots of code
.
.
.
if …
some lines of code
if …
some lines of code
if …
some lines of code
if …
some lines of code
if …
some lines of code
etc
This makes it difficult to see the overall logic
stick it in a method:
def mymethod
return unless …
some lines of code
return unless …
some lines of code
end
lots of code
.
.
mymethod
But if you must keep it within the same scope (lots of local variables
as you say, that you don’t want to pass as arguments), then throw/catch
is another option.
lots of code
.
.
catch(:done) do
throw :done unless …
some lines of code
throw :done unless …
some lines of code
end