Rubocop: Style/ConditionalAssignment: Incorrect detection of violation

Created on 15 Jan 2016  路  2Comments  路  Source: rubocop-hq/rubocop

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 #[].

Most helpful comment

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

All 2 comments

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!

Was this page helpful?
0 / 5 - 0 ratings