Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring conditional variable assignment

I'm working on a project. Currently I have a fairly large conditional statement, that assigns a value to a variable based on some input parameters. So, I have something like this.

if some condition
  x = some value
elsif another condition
  x = a different value
  ...

What's the best way to refactor this? I'm hoping that I might end up with something like

x = some value if some condition || another value if another condition

Is there a pattern for this sort of thing?

like image 629
afkbowflexin Avatar asked Mar 20 '13 22:03

afkbowflexin


4 Answers

Just put the assignment outside the if.

x = if some condition
  some value
elsif another condition
  a different value

Or you could use a Hash.

x = dict[some condition]
like image 130
Chuck Avatar answered Nov 03 '22 01:11

Chuck


It's not a pattern, but an operator. The one you're referring to is the ternary operator:

If Condition is true ? Then value X : Otherwise value Y

Here is an example:

speed = 90
speed > 55 ? puts("I can't drive 55!") : puts("I'm a careful driver")

Using the ternary statement is short, sweet, and does the job.

like image 37
BlackHatSamurai Avatar answered Nov 02 '22 23:11

BlackHatSamurai


x = some condition ? some value : 
    another condition ? a different value : ...
like image 38
ChuckE Avatar answered Nov 03 '22 01:11

ChuckE


A conditional statement is also an expression, so one of the first things you can do, if the variable is the same in each condition, is:

x = if cond1
  expr1
elsif cond2
  expr2
....
end

If the conditions are all states of a single expression, you can make this even neater, using a case statement.

However, the next most obvious re-factoring exercise is to get the big conditional isolated into a method, which should be fed the bare minimum data required to evaluate all the conditions and expressions.

E.g.

# Where conditional is currently, and x assigned, assuming the conditionals
# need a couple of variables . . .
x = foo param1, param2

# Elsewhere
private

def foo p1, p2
  if cond1
    expr1
  elsif cond2
    expr2
  ....
  end
end
like image 29
Neil Slater Avatar answered Nov 03 '22 00:11

Neil Slater