Search code examples
ruby-on-railsrubyconditional-statements

Inverting 2 conditionals in one function


I'm not sure if this is the best title to describe what I'm looking to achieve, but I essentially have 2 conditionals:

  1. current_file.early?
  2. required_file.early?
if current_file.early? && !required_file.early? do
...
end

if !current_file.early? && required_file.early? do
...
end

I think I've been looking at this too long, but I just want to know if there's an easier way for me to simplify this, as they are essentially the inverse of each other. I know I can do a nested if,

current_file.early?
 !required_file.early? && do_something
 required_file.early? && do_something_else

but that's not what I'm looking for either. I'm trying to find something a little more elegant if it exists.


Solution

  • Build a truth table for all the possible conditions as follow:

    Horizontal: current_file.early?
    Vertical: requited_file.early?
    
            true    false
    true    noop    first
    false   second  noop
    

    So there is actually 3 different outcomes: when first condition is true, when second condition is true, otherwise - no operation (noop).

    To make your code clear it would be better to define each condition as separate method with meaningful name.

    def first_cond?
      current_file.early? && !requited_file.early?
    end
    
    def second_cond?
      !current_file.early? && requited_file.early?
    end
    
    if first_cond?
      # when first condition
    elsif second_cond?
      # when second condition
    else
      # noop
    end
    

    And yes, there is no shorter nor elegant way to simplify the given pair of conditions (in terms of formal logic and its rules).