Version: v0.36.0
Custom Cops: _none_
Example code:
# File: ./monkey_patches.rb
class Hash
# Difference between self and other Hash
#
# @param [Hash] b
# @return [Hash]
def deep_diff(b)
a = self
(a.keys | b.keys).inject({}) do |diff, k|
unless a[k] == b[k]
if a[k].respond_to?(:deep_diff) && b[k].respond_to?(:deep_diff)
diff[k] = a[k].deep_diff(b[k])
else
diff[k] = [a[k], b[k]]
end
end
diff
end
end
end
Response:
monkey_patches.rb:11:9: C: Style/ConditionalAssignment: Use the return of the conditional for variable assignment and comparison.
if a[k].respond_to?(:deep_diff) && b[k].respond_to?(:deep_diff)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I know the use of [] _can_ mutate the element at the given index, but it's calling a non-mutating respond_to?. This is the same result if i use #fetch instead of #[].
The cop wants you to change the code to:
diff[k] = if a[k].respond_to?(:deep_diff) && b[k].respond_to?(:deep_diff)
a[k].deep_diff(b[k])
else
[a[k], b[k]]
end
Ah, whoops! I understand the error now.
Confirmed that changing in the specified manner fixed the warning. Thanks!
Most helpful comment
The cop wants you to change the code to: