class RuboCop::Cop::Performance::TimesMap
end
i.to_s
Array.new(9) do |i|
# good
end
i.to_s
9.times.map do |i|
# bad
@example
—-
Array.new(-1) # ArgumentError: negative array size
-1.times{} # does nothing
—-
[source,ruby]
For example:
or less. However, ‘Array.new` raises an error if argument is less than 0.
This cop’s autocorrection is unsafe because ‘Integer#times` does nothing if receiver is 0
@safety
with an explicit array creation.
In most cases such calls can be replaced
Checks for .times.map calls.
def check(node)
def check(node) times_map_call(node) do |map_or_collect, count| next unless handleable_receiver?(node) add_offense(node, message: message(map_or_collect, count)) do |corrector| replacement = "Array.new(#{count.source}#{map_or_collect.arguments.map { |arg| ", #{arg.source}" }.join})" corrector.replace(map_or_collect, replacement) end end end
def handleable_receiver?(node)
def handleable_receiver?(node) receiver = node.receiver.receiver return true if receiver.literal? && (receiver.int_type? || receiver.float_type?) node.receiver.dot? end
def message(map_or_collect, count)
def message(map_or_collect, count) template = if count.literal? "#{MESSAGE}." else "#{MESSAGE} #{MESSAGE_ONLY_IF}." end format(template, count: count.source, map_or_collect: map_or_collect.method_name) end
def on_block(node)
def on_block(node) check(node) end
def on_send(node)
def on_send(node) check(node) end