Skip to content

Commit

Permalink
Fix an incorrect auto-correct for Style/RedundantReturn
Browse files Browse the repository at this point in the history
Fixes standardrb/standard#277.

This PR fixes the following false positive for `Style/RedundantReturn`
when using `return` with splat argument.

```console
% cat example.rb
class MyClass
  def something
    data = [1, 2, 3]
    return *data
  end
end
```

## Before

Auto-corrected to invalid code.

```console
% rubocop --only Style/RedundantReturn -a
(snip)

% cat example.rb
class MyClass
  def something
    data = [1, 2, 3]
    *data
  end
end

% ruby -c example.rb
example.rb:4: syntax error, unexpected '\n', expecting '='
```

## After

Auto-corrected to valid code.

```console
% rubocop --only Style/RedundantReturn -a
(snip)

% cat example.rb
class MyClass
  def something
    data = [1, 2, 3]
    data
  end
end

% ruby -c example.rb
Syntax OK
```
  • Loading branch information
koic committed Mar 22, 2021
1 parent 0427ee4 commit 978578a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_false_positive_for_style_redundant_return.md
@@ -0,0 +1 @@
* [#9631](https://github.com/rubocop/rubocop/issues/9631): Fix an incorrect auto-correct for `Style/RedundantReturn` when using `return` with splat argument. ([@koic][])
4 changes: 4 additions & 0 deletions lib/rubocop/cop/style/redundant_return.rb
Expand Up @@ -71,6 +71,10 @@ def correct_with_arguments(return_node, corrector)
elsif hash_without_braces?(return_node.first_argument)
add_braces(corrector, return_node.first_argument)
end
if return_node.splat_argument?
first_argument = return_node.first_argument
corrector.replace(first_argument, first_argument.source.gsub(/\A\*/, ''))
end

keyword = range_with_surrounding_space(range: return_node.loc.keyword,
side: :right)
Expand Down
17 changes: 17 additions & 0 deletions spec/rubocop/cop/style/redundant_return_spec.rb
Expand Up @@ -54,6 +54,23 @@ def func
RUBY
end

it 'reports an offense for def ending with return with splat argument' do
expect_offense(<<~RUBY)
def func
some_preceding_statements
return *something
^^^^^^ Redundant `return` detected.
end
RUBY

expect_correction(<<~RUBY)
def func
some_preceding_statements
something
end
RUBY
end

it 'reports an offense for defs ending with return' do
expect_offense(<<~RUBY)
def self.func
Expand Down

0 comments on commit 978578a

Please sign in to comment.