ardavis
ardavis

Reputation: 9895

Refactoring method with multiple Logical ANDs

I have a method where I am regularly performing Logical AND on a variable, can it be refactored? This is sort of a 2 part question.

I'm hoping for something similar to a += kind of thing.

def my_method
  var = true

  if condition
    var = var && cond1
  end

  if other_condition
    var = var && cond2
  end

  var
end

Upvotes: 1

Views: 402

Answers (2)

Patrick Oscity
Patrick Oscity

Reputation: 54694

I would use statement modifiers:

def my_method
  res = true
  res &&= cond1 if condition
  res &&= cond2 if other_condition
  res
end

Upvotes: 2

sawa
sawa

Reputation: 168179

  • Is there a short circuit way of doing var = var && condition?

    Yes.

    var &&= condition
    
  • Is there a better way to write this based on multiple conditions and still only return a single boolean?

    def my_method
      (cond1 || !condition      ) &&
      (cond2 || !other_condition)
    end
    

    Edit. p11y's comment is right.

    If you don't like it, you can also write like this using keywords:

    def my_method
      (cond1 if condition      ) and
      (cond2 if other_condition)
    end
    

Upvotes: 2

Related Questions