IRB Rocks!

# Hack your code

Ruby safe operator

Post image

Edited on Jan. 14

Finally, the safe operator was updated from .? to &.. See this comment from Matz.

Ruby Safe operator

Recently, I read in reddit about a new feature in next Ruby minor release: Ruby Safe operator. &. is used to call a method of an Object that can be nil. If the object is different of nil the method will be executed, in the other case, it returns nil.

a = 'Hi!'
b = nil
# Using safe operator...
a&.upcase
# => HI!
b&.upcase
# => nil

This operator comes with the objective to reduce nil verification in our code:

if user && user.avatar && user.avatar.url
  # ...
end

# Same code with &. operator
if user&.avatar&.url
  # ...
end

You can understand it as a native method equivalent to try included in ActiveSupport.

@variable&.method
# With ActiveSupport
@variable.try(:method)

Nil nil nil

As people say in reddit, excessive use of nil checking can come from a bad code design. nil dependency in our application is a bad idea because we always need to carry this verification over all the code, conditionals and nil? will be our best friends.

In the other hands, other people defend "nil pattern". Some gems like andand implement a similar functionality of &..

I think the big problem is the abuse of this operator. There are many situations it very useful, for example, when working with external libraries and APIs.

It has an elegant syntax that is natural to read and easy to write

This is an extract from Ruby slogan we can apply to &. operator:

json['errors'].map { |el| el['name'] } if json['errors']
# With new operator
json['errors']&.map { |el| el['name'] }

&. is easy to read and simplify the code of our applications.

Returned values

class MyString
  def emphasize(string)
     string&.upcase
  end
end

# In other file...
my_string&.emphasize(a_string)
# nil

The result of this code is nil but, where nil value comes? In this case my_string can be nil, but a_string can be too. &. hides some logic of our code, so to use these variables in the following code can cause some problems.

Nil Object

In Ruby all is an Object and nil is not an exception. Some methods from Object class like .nil? get on with &. operator, and this can be a problem in our code logic:

Sometimes I see .nil? in conditionals to initialize a variable:

@var = 'A variable' if @var.nil?

But what happen if we use &. operator?

@var = 'A variable' if @var&.nil?

It's simple, @var never be initialized. You can tell me this is obvious, but it can be confused to new users of Ruby. Remember nil is not an exception of &. operator.

Conclusions

&. help us to keep cleaner our code but it can introduce some problems because the abuse of it hides some logic of our application. Especially, pay attention when you use nil as value in conditionals logic, &. operator can swap executed code.

gem share .gem