diff --git a/changelog/fix_update_variableforce_to_be_able_to.md b/changelog/fix_update_variableforce_to_be_able_to.md new file mode 100644 index 00000000000..301c40a3d35 --- /dev/null +++ b/changelog/fix_update_variableforce_to_be_able_to.md @@ -0,0 +1 @@ +* [#9762](https://github.com/rubocop/rubocop/issues/9762): Update `VariableForce` to be able to handle `case-match` nodes. ([@dvandersluis][]) diff --git a/lib/rubocop/cop/variable_force/branch.rb b/lib/rubocop/cop/variable_force/branch.rb index e66a38438d7..ffc3eb72bb3 100644 --- a/lib/rubocop/cop/variable_force/branch.rb +++ b/lib/rubocop/cop/variable_force/branch.rb @@ -226,6 +226,21 @@ def always_run? end end + # case target + # in pattern # in_pattern + # else + # else_body + # end + class CaseMatch < Base + define_predicate :target?, child_index: 0 + define_predicate :in_pattern?, child_index: 1..-2 + define_predicate :else_body?, child_index: -1 + + def always_run? + target? + end + end + # for element in collection # loop_body # end diff --git a/spec/rubocop/cop/lint/useless_assignment_spec.rb b/spec/rubocop/cop/lint/useless_assignment_spec.rb index d3e6245742b..b0e0ee29e9b 100644 --- a/spec/rubocop/cop/lint/useless_assignment_spec.rb +++ b/spec/rubocop/cop/lint/useless_assignment_spec.rb @@ -1416,4 +1416,19 @@ def some_method(environment) end end end + + context 'inside a `case-match` node', :ruby27 do + it 'does not register an offense when the variable is used' do + expect_no_offenses(<<~RUBY) + case '0' + in String + res = 1 + else + res = 2 + end + + do_something(res) + RUBY + end + end end