Hashes and Arrays can be accessed using the .[](key_or_index)
syntax.
irb(main):001> array = [1]
=> [1]
irb(main):002> array.[](0)
=> 1
irb(main):003> array. [](0)
=> 1
Even when this syntax is used, I expect Layout/SpaceBeforeBrackets
to properly detect the presence of the space and offer an appropriate autocorrection.
collection. [](index_or_key)
^ Remove the space before the opening brackets.
Actual behavior
However, when there is a space like this, it incorrectly reports the offense position.
collection. [](index_or_key)
^^ Remove the space before the opening brackets.
To make matters worse, when autocorrect is run, it transforms the code into one that results in a syntax error.
collection[](index_or_key)
Steps to reproduce the problem
I verified it using an RSpec example:
diff --git a/spec/rubocop/cop/layout/space_before_brackets_spec.rb b/spec/rubocop/cop/layout/space_before_brackets_spec.rb index d7bcd9f01..49b03d41e 100644 --- a/spec/rubocop/cop/layout/space_before_brackets_spec.rb +++ b/spec/rubocop/cop/layout/space_before_brackets_spec.rb @@ -59,6 +59,17 @@ RSpec.describe RuboCop::Cop::Layout::SpaceBeforeBrackets, :config do RUBY end + it 'registers an offense and corrects when using space between dot and left bracket' do + expect_offense(<<~RUBY) + collection. [](index_or_key) + ^ Remove the space before the opening brackets. + RUBY + + expect_correction(<<~RUBY) + collection.[](index_or_key) + RUBY + end + it 'does not register an offense when using space between method call and left brackets' do expect_no_offenses(<<~RUBY) do_something [item_of_array_literal]
Failures:
1) RuboCop::Cop::Layout::SpaceBeforeBrackets when referencing registers an offense and corrects when using space between dot and left bracket
Failure/Error: expect(actual_annotations).to eq(expected_annotations), ''
Diff:
@@ -1,3 +1,3 @@
collection. [](index_or_key)
- ^ Remove the space before the opening brackets.
+ ^^ Remove the space before the opening brackets.
# ./lib/rubocop/rspec/expect_offense.rb:130:in 'RuboCop::RSpec::ExpectOffense#expect_offense'
# ./spec/rubocop/cop/layout/space_before_brackets_spec.rb:63:in 'block (3 levels) in <top (required)>'
RuboCop version
$ bundle exec rubocop -V
1.76.2 (using Parser 3.3.8.0, rubocop-ast 1.45.1, analyzing as Ruby 2.7, running on ruby 3.4.2) [x86_64-linux]
- rubocop-performance 1.25.0
- rubocop-rake 0.7.1
- rubocop-rspec 3.6.0
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4