Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Do not chain ordinary method call after safe navigation operator

I am unable to find the problem with this rubocop warning Do not chain ordinary method call after safe navigation operator.

price_array = user&.user_price_fluctuation&.market_price&.sort << user_price&.sort
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Just think about what the safe navigation operator does: it evaluates to nil if the object the method is being called on is nil.

So, if foo is not nil, then foo&.bar will call bar on foo, but if foo is nil, then foo&.bar is nil, too.

That is why it does not make sense to chain an ordinary method call after the safe navigation operator:

foo&.bar.baz

If foo is not nil, this will work, but if foo is nil, then foo&.bar is also nil and you are trying to call nil.baz, which does not work. In other words: the code only works if you already know that foo is not nil, but then you would not need the safe navigation operator in the first place!

The same is true for your code: if any if user or any of the intermediate values in the chain is nil, then you are calling nil << something, which does not work. You need to make sure the whole chain uses the safe navigation operator:

price_array = user&.user_price_fluctuation&.market_price&.sort&.<<(user_price&.sort)

Of course, the even better solution is to forget about the safe navigation operator and instead figure out where those nil values are coming from in the first place and fix it.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!