Home > front end >  Do not chain ordinary method call after safe navigation operator
Do not chain ordinary method call after safe navigation operator

Time:03-22

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

CodePudding user response:

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.

CodePudding user response:

This should work

price_array = user&.user_price_fluctuation&.market_price&.sort
price_array << user_price&.sort
  • Related