I often find myself doing things like this:
do_something if x && x == y
In other works, do something if x
is not nil, and it has a value of y
.
It would be nice if I could do something like this instead:
do_something if x &&== y
Is there an operator that does this?
Responses to comments:
x == y
- The problem with this, is that it only tests existence (not nil) if the value of y
is known. If y
is itself nil
then the check fails. So you could end up doing:
y && x == y
x ||= y
- This would assign the value of y
to x
if x
is nil. That's not what I'm looking for. x &&= y
doesn't work either for the same reason - it changes the value of x
to y
if x
exists.
An example: in my current scenario I want to check that a user has passed to a controller the token associated with them, but I also want to ensure that the token has been assigned. Something like:
do_something if user.token && user.token == params[:token]