How to run a series of checks?
I'm trying to run a series of if/else statements but right now they basically end up being deeply nested if/else statements.
I'm ultimately wanting to say: If A isn't true, run B. If B isn't true, run C. If C isn't true, run D, and so on.
Crude example:
开发者_StackOverflow中文版if a == b
return true
else
c = d/e
if c = a
return true
else
g = h*i
if g == true
return true
else
return false
end
end
end
Firstly, you don't need else
when you're returning from the first branch of an if
, so your
if (condition)
return true
else
# otherwise code
end
should always be written
if (condition)
return true
# otherwise code
This can be written more succinctly in Rails:
return true if (condition)
# otherwise code
Secondly, this pattern is particularly hideous:
if (condition)
return true
else
return false
end
You should always prefer to simply return the condition, which is exactly equivalent (assuming the condition evaluates to boolean true/false):
return (condition)
Put these together and you get this drastically simplified, un-nested but identical code:
return true if a == b
c = d/e
return true if c == a
g = h*i
return g == true
return true if a == b
c = d/e
return true if c == a
g = h*i
return true if g == true
return false
You can use statement modifiers in Ruby to add conditional logic. So, instead of nested if statements, you can just do what you plan to do if some condition is met.
From your example, since you return when success is detected, there is no reason to nest the if statements. The following:
return true if a == b
c = d/e
return true if c == a
g = h*i
return g
would do exactly the same as your example. (Actually, I don' think my final return statement is required either)
精彩评论