Is there an ideomatic or shorter way to "compare two values but don't allow them to be nil".
One way would be:
(!left.nil? || !right.nil?) && (left == right)
One of the nil checks could be omitted, here, but I left it in the example, to show the intent better.
Is there a method in Ruby core, on Kernel or BasicObject, next to equal?, eql?, == and such that matches this?
I aim at something similar to what e.g. minitest assert_equal does (edited for brevity, nil-check at line 5):
def assert_equal exp, act, msg = nil
msg = message(msg, E) { diff exp, act }
result = assert exp == act, msg
if nil == exp then
refute_nil exp, "Use assert_nil if expecting nil."
end
result
end
In my case this is for an autorization system where I repeatedly have to guard against both sides being nil. E.g.
class ContactPolicy < ApplicationPolicy
def add?
!actor.id.nil? && subject.id == actor.id
end
end
After repeating that pattern in various forms, I wondered if there is not a better Ruby-ism for this. I am now leaning towards a refactoring using null-objects that have a def ==(other) which always return false. The question of whether this "equal but not nil" remains interesting though.