Skip to content

Style/SafeNavigation cop incorrectly transforms arithmetic operations, leading to syntax errors. #14286

@marocchino

Description

@marocchino

The Style/SafeNavigation cop incorrectly transforms expressions involving arithmetic operations and the ternary operator with safe navigation, resulting in invalid Ruby syntax.

r ? r.to_i + 1 : nil

Expected behavior

r&.then { |r| r.to_i + 1 }
# or
r&.to_i&.+(1)
# or No offense

Actual behavior

# transform to
r&.to_i&. + 1

Steps to reproduce the problem

$ echo "r ? r.to_i + 1 : nil" | rubocop --autocorrect-all --stdin test.rb
Inspecting 1 file
W

Offenses:

test.rb:1:1: C: [Corrected] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
r ? r.to_i + 1 : nil
^
test.rb:1:1: C: [Corrected] Style/SafeNavigation: Use safe navigation (&.) instead of checking if an object exists before calling the method.
r ? r.to_i + 1 : nil
^^^^^^^^^^^^^^^^^^^^
test.rb:2:1: C: [Corrected] Layout/EmptyLineAfterMagicComment: Add an empty line after magic comments.
r&.to_i + 1
^
test.rb:2:8: W: [Corrected] Lint/SafeNavigationChain: Do not chain ordinary method call after safe navigation operator.
r&.to_i + 1
       ^^^^
test.rb:3:10: C: [Corrected] Layout/SpaceAroundMethodCallOperator: Avoid using spaces around a method call operator.
r&.to_i&. + 1
         ^

1 file inspected, 5 offenses detected, 5 offenses corrected
====================
# frozen_string_literal: true

r&.to_i&.+ 1

RuboCop version

$ rubocop -V
1.76.1 (using Parser 3.3.8.0, Prism 1.4.0, rubocop-ast 1.45.1, analyzing as Ruby 3.4, running on ruby 3.4.1) [arm64-darwin24]
  - rubocop-capybara 2.22.1
  - rubocop-factory_bot 2.27.1
  - rubocop-performance 1.25.0
  - rubocop-rails 2.32.0
  - rubocop-rspec 3.6.0
  - rubocop-rspec_rails 2.31.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions