Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading