Style/ConditionalAssignment: Use the return of the conditional for variable assignment and comparison

Viewed 1950

Below is my Ruby on Rails code -

inactive_list = [1,2,3,4,5]
raw_data = []

data = {
  name: "Test",
  full_name: "Test data"
}
if inactive_list.include? <<id of data>>
  data[:active] = false
else
  data[:active] = true
end

raw_data << data

I am getting Rubocop linting error for if...else statement. I tried making several changes but unable to fix linting Rubocop error.

C: Style/ConditionalAssignment: Use the return of the conditional for variable assignment and comparison.
2 Answers

Instead of

if inactive_list.include? <<id of data>>
  data[:active] = false
else
  data[:active] = true
end

you can just write

data[:active] = !inactive_list.include? <<id of data>>

Or when you are using Rails then you can use exclude? instead of the negation of include?:

data[:active] = inactive_list.exclude? <<id of data>>

Full example:

data = {
  name: "Test",
  full_name: "Test data",
  active: inactive_list.exclude?(<<id of data>>)
}

In general, Style/ConditionalAssignment rubocop rule (cop) requires you to change these 2 repetitive assignments:

if condition
  variable = value1
else
  variable = value2
end

to a single conditional assignment:

variable = if condition
             value1
           else
             value2
           end

In your case, the smallest change Rubocop requires is to change this:

if inactive_list.include? <<id of data>>
  data[:active] = false
else
  data[:active] = true
end

to that:

data[:active] = if inactive_list.include? <<id of data>>
                  false
                else
                  true
                end

See @spickermann's answer for a shorter and more elegant further change, which is possible because include? returns true or false, which happens to be exactly what you need for the assignment. So you do not need to explicitly assign true or false here, just negate it using !, a common programming idiom:

data[:active] = !inactive_list.include? <<id of data>>

SEE ALSO:

Array include? method: https://ruby-doc.org/core-2.7.0/Array.html#method-i-include-3F

RuboCop::Cop::Style::ConditionalAssignment : https://www.rubydoc.info/github/bbatsov/RuboCop/RuboCop/Cop/Style/ConditionalAssignment

Check for if and case statements where each branch is used for assignment to the same variable when using the return of the condition can be used instead.

Related