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?)
精彩评论