Skip to main content

Command Palette

Search for a command to run...

ruby safe navigation operator (&.)

Published
1 min read
P

I am a full-stack Ruby on Rails developer with experience in PostgreSQL, Docker, Heroku, and performance optimization. I love exploring new technology stacks and have recently developed an interest in mobile app development using Flutter. My skills in test-driven development and fixing security vulnerabilities have helped me deliver high-quality, reliable code. I am also currently learning about machine learning and its applications in real-world problem-solving. I bring a unique combination of technical expertise, creative problem-solving, and a passion for learning to any team. I am committed to delivering elegant and efficient software solutions and excited to contribute to an innovative and dynamic team that shares this vision.

This post you will learn about the most interesting addition to Ruby 2.3.0, the Safe Navigation Operator(&.).

Scenario

Lets say we have a cart object, which belongs to an owner and we want to know the email of the owner.

Most common solution we find Devs doing in this situation is:

cart && cart.owner && cart.owner.email

which is checking if cart is present, than check cart.owner and if it present than return cart.owner.email as a result, which is tidious to write and doesn't looks good, also imagine, if there are multi level associations to work on.

Now another solution is:

cart.try(:owner).try(:email)

bit shorter and cleaner than above solution but we can improve this by using &. operator:

cart&.owner&.email

It will return the email address of owner, if cart and owner present, otherwise, return nil.

More from this blog

T

The Developers Journey

41 posts

I am a full-stack Ruby on Rails developer with experience in TDD, PostgreSQL, Docker, Heroku, performance optimization and Flutter mobile app development.