ReggieB
ReggieB

Reputation: 8212

Is there an "&& Equals" operator in Ruby

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]

Upvotes: 3

Views: 1198

Answers (1)

hahcho
hahcho

Reputation: 1409

If you are using ruby > 2.3.0 you can use the &. operator: x&.== y. It basically does what .try does in Rails if the value of the operand is different than nil it calls the method and returns its result. If the value is nil it returns nil so you can do things like: do_i_exist&.does_the_result_exist&.nil?

See: What does &. (ampersand dot) mean in Ruby?

Upvotes: 6

Related Questions