Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda