开发者

Better way to write if condition

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜