Avoiding NoMethodError with Safe Navigation Operator in Ruby ~2.3

George Chkhvirkia
1 min readFeb 19, 2019

--

Any Ruby/Rails dev had a situation when he tried to call object method, and he got hit by NoMethodError. E.g:

task = Task.find(params[:id])project_name = task.project.name# > NoMethodError: undefined method `name’ for nil:NilClass

task has no project assigned to it, so we get an error. We can avoid it by having checks like this:

task.project && task.project.name# or
task.project.present? && task.project.name.present?
# or
task.try(:project).try(:name)

All of the above are too verbose, sometimes uncomfortable to read. You can try those, or use Method Delegation, you can read about it here:

Or! There is new & operator in Ruby ~2.3 called Safe Navigation Operator, and its very easy to use:

task&.project
# returns nil
task&.project&.name
# also returns nil, instead of NoMethodError
# or returns the actual value of `name`

No extra lines of code, no extra logic — only safety and comfort.

--

--