Skip to content

Commit

Permalink
Support any expression as the start index in Style/SlicingWithRange (#…
Browse files Browse the repository at this point in the history
…7967)

Supports any expression as start index (only int previously).
Still correctly ignores startless range.
  • Loading branch information
zverok committed May 14, 2020
1 parent d525092 commit 9272fda
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -10,6 +10,7 @@

* [#7953](https://github.com/rubocop-hq/rubocop/issues/7953): Fix an error for `Lint/AmbiguousOperator` when a method with no arguments is used in advance. ([@koic][])
* [#7962](https://github.com/rubocop-hq/rubocop/issues/7962): Fix a false positive for `Lint/ParenthesesAsGroupedExpression` when heredoc has a space between the same string as the method name and `(`. ([@koic][])
* [#7967](https://github.com/rubocop-hq/rubocop/pull/7967): `Style/SlicingWithRange` cop now supports any expression as its first index. ([@zverok][])

### Changes

Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/style/slicing_with_range.rb
Expand Up @@ -19,7 +19,7 @@ class SlicingWithRange < Cop

MSG = 'Prefer ary[n..] over ary[n..-1].'

def_node_matcher :range_till_minus_one?, '(irange (int _) (int -1))'
def_node_matcher :range_till_minus_one?, '(irange !nil? (int -1))'

def on_send(node)
return unless node.method?(:[]) && node.arguments.count == 1
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/style/slicing_with_range_spec.rb
Expand Up @@ -23,6 +23,17 @@
RUBY
end

it 'reports an offense for slicing from expression to ..-1' do
expect_offense(<<~RUBY)
ary[fetch_start(true).first..-1]
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer ary[n..] over ary[n..-1].
RUBY

expect_correction(<<~RUBY)
ary[fetch_start(true).first..]
RUBY
end

it 'reports no offense for excluding end' do
expect_no_offenses(<<~RUBY)
ary[1...-1]
Expand Down

0 comments on commit 9272fda

Please sign in to comment.