14
.
11
.
2023
20
.
09
.
2022
Ruby on Rails
Backend
Ruby
Tutorial

Safe navigation operator '&.' vs '.try' in Rails

Mateusz Woźniczka
Ruby Developer

Safe navigation operator '&.' vs '.try' in Rails

We are back to our Blog app, and this time we want to get the name of the post's author. The task is really straightforward, and we end up with the following piece of code:

post.author.name

We will get our desired result, only if post.author and post.author.name are defined - otherwise, we will end up with undefined method error. If we want to avoid those errors, we can make use of some ifs:

if post
  if post.author
    if post.author.name
      post.author.name
    end
  end
end

This solution gets the job done, but looks extremely bad. Fortunately, Ruby provides a safe navigation operator &. and Rails (or ActiveSupport to be more specific) provides the try method, that can help avoid undefined method exceptions without extensive use of if statements.

In this post, we will compare both of those methods, and look for the differences between them.

Examples

Happy path

First, let's see how they behave when everything is defined.

author = Author.new(name: 'Joe')
post = Post.new(author: author)

post.author.name
> "Joe"

post&.author&.name
> "Joe"

post.try(:author).try(:name)
> "Joe"

There are no big surprises. When there is no nil along the chain both &. and try return the author's name.

Post without an author

post = Post.new

post.author.name
> NoMethodError (undefined method 'name' for nil:NilClass)

post&.author&.name
> nil

post.try(:author).try(:name)
> nil

As expected, both methods return nil instead of calling the name method on an empty author.

Nil post

Let's see how both methods behave when they are used to call chained undefined methods for nil

nil.author.name
> NoMethodError (undefined method 'author' for nil:NilClass)

nil&.author&.name
> nil

nil.try(:author).try(:name)
> nil

Just like in the previous example both methods returned nil instead of calling the author method nil.

Calling post's undefined method

Now let's get back to post, and see what happens when we try to call an undefined method

post = Post.new

post.undefined_method
> NoMethodError (undefined method 'undefined_method' for <Post:0x00007fe4ee8f5e50>)

post&.undefined_method
> NoMethodError (undefined method 'undefined_method' for <Post:0x00007fe4ee8f5e50>)

post.try(:undefined_method)
> nil

Here is the first difference between the discussed functions. Safe navigation operator returns nil only if the receiver is nil as well - it does not do any validation of called methods. On the other hand, try is returning nil whenever the receiver does not respond to the call.

Calling nil's defined method

Let's go back to the example with nil as the receiver of the first call, but this time we will extend NilClass, so the called method is actually defined.

class NilClass
  def name
    'called nil name'
  end
end

nil.name
> "called nil name"

Now, nil respond to the name method. Let’s see how both methods are handling that:

nil&.name
> nil

nil.try(:name)
> nil

The safe navigation operator behaves as expected - it does not care about the method implementation - it checks only if the receiver is nil. Method try is behaving in the same matter - if the receiver is nil it is not checking if it responds to called method, instead, it returns nil as well.

Wrap up

Safe navigation operator &. is provided by Ruby. It returns nil only if the receiver of the method is nil as well. It does not check if called method is defined.

Rails provides us with the try method, which checks if the receiver (which is not nil) responds to the called method, and if not it returns nil instead of throwing an exception.

Mateusz Woźniczka
Ruby Developer

Check my Twitter

Check my Linkedin

Did you like it? 

Sign up To VIsuality newsletter

READ ALSO

N+1 in Ruby on Rails

14
.
11
.
2023
Katarzyna Melon-Markowska
Ruby on Rails
Ruby
Backend

Turbo Streams and current user

29
.
11
.
2023
Mateusz Bilski
Hotwire
Ruby on Rails
Backend
Frontend

Showing progress of background jobs with Turbo

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Ruby
Hotwire
Frontend
Backend

Table partitioning in Rails, part 1 - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Postgresql
Backend
Ruby on Rails

Table partitioning types - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Postgresql
Backend

Indexing partitioned table - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Backend
Postgresql
SQL Views in Ruby on Rails

SQL views in Ruby on Rails

14
.
11
.
2023
Jan Grela
Backend
Ruby
Ruby on Rails
Postgresql
Design your bathroom in React

Design your bathroom in React

14
.
11
.
2023
Bartosz Bazański
Frontend
React
Lazy Attributes in Ruby - Krzysztof Wawer

Lazy attributes in Ruby

14
.
11
.
2023
Krzysztof Wawer
Ruby
Software

Exporting CSV files using COPY - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Postgresql
Ruby
Ruby on Rails
Michał Łęcicki - From Celluloid to Concurrent Ruby

From Celluloid to Concurrent Ruby: Practical Examples Of Multithreading Calls

14
.
11
.
2023
Michał Łęcicki
Backend
Ruby
Ruby on Rails
Software

Super Slide Me - Game Written in React

14
.
11
.
2023
Antoni Smoliński
Frontend
React
Jarek Kowalewski - ILIKE vs LIKE/LOWER - Postgres Stories

ILIKE vs LIKE/LOWER - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Ruby
Ruby on Rails
Postgresql

A look back at Friendly.rb 2023

14
.
11
.
2023
Cezary Kłos
Conferences
Ruby

Debugging Rails - Ruby Junior Chronicles

14
.
11
.
2023
Piotr Witek
Ruby on Rails
Backend
Tutorial

GraphQL in Ruby on Rails: How to Extend Connections

14
.
11
.
2023
Cezary Kłos
Ruby on Rails
GraphQL
Backend
Tutorial

Tetris on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Backend
Frontend
Hotwire

EURUKO 2023 - here's what you've missed

14
.
11
.
2023
Michał Łęcicki
Ruby
Conferences

Easy introduction to Connection Pool in ruby

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Backend
Ruby
Tutorial

When crazy ideas bring great time or how we organized our first Conference!

04
.
12
.
2023
Alexander Repnikov
Ruby on Rails
Conferences
Visuality

Stacey Matrix & Takeaways - why does your IT project suck?

14
.
11
.
2023
Wiktor De Witte
Project Management
Business

A simple guide to pessimistic locking in Rails

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Backend
Ruby
Tutorial

Poltrax design - story of POLTRAX (part 3)

04
.
12
.
2023
Mateusz Wodyk
Startups
Business
Design

Writing Chrome Extensions Is (probably) Easier Than You Think

14
.
11
.
2023
Antoni Smoliński
Tutorial
Frontend
Backend