开发者

Better way to write if condition

开发者 https://www.devze.com 2023-01-11 04:19 出处:网络
Is 开发者_StackOverflow中文版there any better way to write this condition? if (self.expense.nil? && self.income.nil?) || (!self.expense.nil? && !self.income.nil?)

Is 开发者_StackOverflow中文版there any better way to write this condition?

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


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.


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.


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?)

0

精彩评论

暂无评论...
验证码 换一张
取 消