diff --git a/changelog/fix_false_positive_for_style_method_def_parentheses.md b/changelog/fix_false_positive_for_style_method_def_parentheses.md new file mode 100644 index 000000000000..08dd28e1a271 --- /dev/null +++ b/changelog/fix_false_positive_for_style_method_def_parentheses.md @@ -0,0 +1 @@ +* [#10321](https://github.com/rubocop/rubocop/issues/10321): Make `Style/MethodDefParentheses` aware of Ruby 3.1's anonymous block forwarding. ([@koic][]) diff --git a/lib/rubocop/cop/style/method_def_parentheses.rb b/lib/rubocop/cop/style/method_def_parentheses.rb index 949044901eb4..441e78c3c7b4 100644 --- a/lib/rubocop/cop/style/method_def_parentheses.rb +++ b/lib/rubocop/cop/style/method_def_parentheses.rb @@ -6,8 +6,13 @@ module Style # This cop checks for parentheses around the arguments in method # definitions. Both instance and class/singleton methods are checked. # - # This cop does not consider endless methods, since parentheses are - # always required for them. + # Regardless of style, parentheses are necessary for: + # + # 1. Endless methods + # 2. Argument lists containing a `forward-arg` (`...`) + # 3. Argument lists containing an anonymous block forwarding (`&`) + # + # Removing the parens would be a syntax error here. # # @example EnforcedStyle: require_parentheses (default) # # The `require_parentheses` style requires method definitions @@ -133,9 +138,9 @@ def forced_parentheses?(node) # Regardless of style, parentheses are necessary for: # 1. Endless methods # 2. Argument lists containing a `forward-arg` (`...`) + # 3. Argument lists containing an anonymous block forwarding (`&`) # Removing the parens would be a syntax error here. - - node.endless? || node.arguments.any?(&:forward_arg_type?) + node.endless? || node.arguments.any?(&:forward_arg_type?) || anonymous_block_arg?(node) end def require_parentheses?(args) @@ -163,6 +168,12 @@ def unwanted_parentheses(args) unexpected_style_detected 'require_parentheses' end end + + def anonymous_block_arg?(node) + return false unless (last_argument = node.arguments.last) + + last_argument.blockarg_type? && last_argument.name.nil? + end end end end diff --git a/spec/rubocop/cop/style/method_def_parentheses_spec.rb b/spec/rubocop/cop/style/method_def_parentheses_spec.rb index 8517892d13d3..117cf09dd528 100644 --- a/spec/rubocop/cop/style/method_def_parentheses_spec.rb +++ b/spec/rubocop/cop/style/method_def_parentheses_spec.rb @@ -99,6 +99,14 @@ def foo(...) end RUBY end + + it 'requires parens for anonymous block forwarding', :ruby31 do + expect_no_offenses(<<~RUBY) + def foo(&) + bar(&) + end + RUBY + end end shared_examples 'endless methods' do