class RuboCop::Cop::Style::ArrayCoercion
Array(paths).each { |path| do_something(path) }
# good (and a bit more readable)<br><br>.each { |path| do_something(path) }
# bad (always creates a new Array instance)
paths.each { |path| do_something(path) }
paths = [paths] unless paths.is_a?(Array)
# bad
@example
—-
Array(Time.now) #=> [14, 16, 14, 16, 9, 2021, 4, 259, true, “EDT”]<br> #=> [#<Time …>]
Array({a: ‘b’}) #=> [[:a, ‘b’]]
[{a: ‘b’}] #= [{a: ‘b’}]
Array(nil) #=> []
#=> [nil]
—-
[source,ruby]
For example:
different than just wrapping the argument in an array).
on how the argument is handled by ‘Array()` (which can be
the argument of `Array()` is (or could be) nil or depending
This cop is unsafe because a false positive may occur if
@safety
The cop is disabled by default due to safety concerns.
This cop enforces the use of `Array()` instead of explicit `Array` check or `[*var]`.
def on_array(node)
def on_array(node) return unless node.square_brackets? array_splat?(node) do |arg_node| message = format(SPLAT_MSG, arg: arg_node.source) add_offense(node, message: message) do |corrector| corrector.replace(node, "Array(#{arg_node.source})") end end end
def on_if(node)
def on_if(node) unless_array?(node) do |var_a, var_b, var_c| if var_a == var_b && var_c == var_b message = format(CHECK_MSG, arg: var_a) add_offense(node, message: message) do |corrector| corrector.replace(node, "#{var_a} = Array(#{var_a})") end end end end