How can I idiomatically write a doubly nested if/else in Ruby?

Suppose I have some code like:

def set_reminder(cond_one: false, cond_two: false)
  if cond_two
    if cond_one
      outcome_a
    else
      outcome_b
    end
  else
    if cond_one
      outcome_c
    else
      outcome_d
    end
  end
end

How can I more elegantly write a function like this, which has 4 potential results (one for each combination of possible cond_one and cond_two values)?

I’m not satisfied with this version, using an if/else statement with another if/else in both branches. In the actual code, the outcomes are already complex expressions, so writing something like return outcome_a if cond_one && cond_two (for all 4 outcomes) would be unwieldy.

>Solution :

Ruby has a very powerful case expression that can be used for this sort of thing. Consider

def set_reminder(cond_one: false, cond_two: false)
  case [cond_one, cond_two]
  when [true, true] then outcome_a
  when [true, false] then outcome_b
  when [false, true] then outcome_c
  when [false, false] then outcome_d
  end
end

As pointed out in the comments, though, consider having your arguments convey more than just "pair of Booleans". See Boolean blindness for a good discussion on this.

Leave a Reply