class RuboCop::Cop::Style::RedundantSelfAssignment
self.foo += ary
foo.concat(ary)
# good
self.foo = foo.concat(ary)
# bad
hash.merge!(other)
args += foo
args.concat(foo)
# good
hash = hash.merge!(other)
args = args.concat(ary)
# bad
@example
its receiver in place.
user defined methods having one of the expected names, but not modifying
This cop is marked as unsafe, because it can produce false positives for
modification methods.
This cop checks for places where redundant assignments are made for in place
def correction_range(node)
def correction_range(node) range_between(node.source_range.begin_pos, node.first_argument.source_range.begin_pos) end
def method_returning_self?(method_name)
def method_returning_self?(method_name) METHODS_RETURNING_SELF.include?(method_name) end
def on_lvasgn(node)
def on_lvasgn(node) lhs, rhs = *node receiver, method_name, = *rhs return unless receiver && method_returning_self?(method_name) receiver_type = ASSIGNMENT_TYPE_TO_RECEIVER_TYPE[node.type] return unless receiver.type == receiver_type && receiver.children.first == lhs message = format(MSG, method_name: method_name) add_offense(node.loc.operator, message: message) do |corrector| corrector.replace(node, rhs.source) end end
def on_send(node)
def on_send(node) # TODO: replace with #end_with? after supporting only ruby >= 2.7 return unless node.method_name.match?(/=$/) return unless redundant_assignment?(node) message = format(MSG, method_name: node.first_argument.method_name) add_offense(node.loc.operator, message: message) do |corrector| corrector.remove(correction_range(node)) end end
def redundant_assignment?(node)
def redundant_assignment?(node) receiver_name = node.method_name.to_s[0...-1].to_sym redundant_self_assignment?(node, receiver_name) || redundant_nonself_assignment?(node, node.receiver, receiver_name) end