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
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
RuboCop doesn't make a complaint.
$ rubocop -V
[warning skipped]
0.42.0 (using Parser 2.3.1.2, running on ruby 2.4.0 x86_64-darwin14)
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.
Most helpful comment
If we add support for
x = some_value unless defined?(x)orx = 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 isfalse.