Rubocop: Detect opportunities for ||= (double pipe equals)

Created on 24 Jan 2017  路  4Comments  路  Source: rubocop-hq/rubocop

RuboCop doesn't detect when code can be written using ||=. Should it do so?

The Ruby Style Guide recommends this coding style: https://github.com/bbatsov/ruby-style-guide#double-pipe-for-uninit


Expected behavior

Given code like

def my_method(arr)
  x = arr.find(&:even?)

  x = x ? x : 42
  "Result is #{x}"
end

puts my_method([3, 5, 2])

I would expect RuboCop to tell me to use x ||= 42 rather than the ternary operator

Actual behavior

RuboCop doesn't make a complaint.

RuboCop version

$ rubocop -V
[warning skipped]
0.42.0 (using Parser 2.3.1.2, running on ruby 2.4.0 x86_64-darwin14)
feature request

Most helpful comment

If we add support for x = some_value unless defined?(x) or x = some_value if x.nil?, then I think they should be configurable. ||= is going to assign the value if the variable is falsy. In most cases, then change should be safe, but there are times where you would not want to assign the variable if the variable is false.

All 4 comments

Makes perfect sense to me. 馃榾

Other possible formats that should be checked for would be

x = x || some_value
x = some_value unless x
x = some_value unless defined?(x)

Think it's worth adding:

x = some_value if x.nil?

If we add support for x = some_value unless defined?(x) or x = some_value if x.nil?, then I think they should be configurable. ||= is going to assign the value if the variable is falsy. In most cases, then change should be safe, but there are times where you would not want to assign the variable if the variable is false.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Ana06 picture Ana06  路  3Comments

AndreiMotinga picture AndreiMotinga  路  3Comments

deivid-rodriguez picture deivid-rodriguez  路  3Comments

herwinw picture herwinw  路  3Comments

bbatsov picture bbatsov  路  3Comments