1
action&.!=:click

Can somebody please explain to me what is the meaning of this in ruby and where I can get some explanations? I try to search ruby documentation, but no luck with this kind of 'chaining' operators

:click is symbol

!= is not equal

but I have no idea about &.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
user_pruser
  • 422
  • 2
  • 13

1 Answers1

2

What looks like one operator in the middle (&.!=) is actually 1 operator and 1 method call : &. followed by != with :click as argument:

action &. != :click

It checks if action is not nil but distinct from :click:

action = nil
action&.!=:click
# => nil

action = :not_click
action&.!=:click
# => true

action = :click
action&.!=:click
# => false

action = false
action&.!=:click
# => true

It's an abusive way to use &. in my humble opinion. &. is called a "safe navigation operator", because it prevents you from calling undefined methods on nil objects.

!= is defined for any object though, so there's nothing safe about using &. before !=.

You could write :

!(action.nil? || action == :click)

or

!action.nil? && action != :click

or even:

![nil, :click].include?(action)
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124