Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More powerful SlicingWithRange #7967

Merged
merged 1 commit into from May 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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][])

koic marked this conversation as resolved.
Show resolved Hide resolved
### 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