Skip to content

Instantly share code, notes, and snippets.

@AndyObtiva
Created December 13, 2011 16:41
Show Gist options
  • Save AndyObtiva/1472846 to your computer and use it in GitHub Desktop.
Save AndyObtiva/1472846 to your computer and use it in GitHub Desktop.
Non-recommended Ruby multi-line if conditional assignment of value
# Not easy to parse and read.
value = if conditional
# do some work
# do more work
value1
else
# do some work
# do more work
value2
end
# use value for something
# Clearer approach for cases when if branches are multi-line even if a little more verbose
value = nil # this line helps clarify the scope for the value, also needed if there is no else block.
if conditional
# do some work
# do more work
value = value1
else
# do some work
# do more work
value = value2
end
# use value for something
# I tend to prefer the extract method approach though
value = get_value
# use value for something
# Method usually has a more descriptive name clarifying this step in the algorithm
def get_value
if conditional
# do some work
# do more work
value1
else
# do some work
# do more work
value2
end
end
# Of course if branches were not multi line, just use the ternary operator
value = cond ? value1 : value2
@turnerking
Copy link

#What about this
value = 
  if conditional
    # do some work
    # do more work
    value1
  else
    # do some work
    # do more work
    value2
  end

@AndyObtiva
Copy link
Author

tking, that looks better, but I've seen examples that made it tough to connect the end of the if/else conditional to the assignment of the value since they were more than a page long. Of course, long methods is an orthogonal problem, but compounding that with multi line if/else value assignment made it even harder to discern the high-level algorithm/workflow at a glance. From your tweet, it seems like you and I agree that the extract method approach works best generally as it abstracts that step of the algorithm into a one line statement (provided the get_value method is named properly to describe the algorithm step clearly)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment