krunal shah
krunal shah

Reputation: 16339

Better way to write if condition

Is there any better way to write this condition?

if (self.expense.nil? && self.income.nil?) || (!self.expense.nil? && !self.income.nil?)
  puts "test"
end

Upvotes: 3

Views: 1074

Answers (3)

Mark Byers
Mark Byers

Reputation: 838226

You are testing to see if the expressions are both true or both false. Try this:

if (self.expense.nil? == self.income.nil?)

You don't care whether they are both true or both false, just that they are the same.

Upvotes: 18

tybro0103
tybro0103

Reputation: 49703

Despite the logic, since you're using an if to check for nil you could shorten the code like so:

if ((expense && income) || (!expense && !income))
  puts "test"
end

Correct me if I'm wrong.

Upvotes: 1

Albinoswordfish
Albinoswordfish

Reputation: 1957

You could use Demorgan's law for the second half of the if condition

so (!self.expense.nil? && !self.income.nil?) becomes !(self.expense.nil? || self.income.nil?)

Upvotes: 0

Related Questions