123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Performance::TimesMap

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, AutoCorrector, Base
Instance Chain:
self, Base
Inherits: Base
  • Object
Defined in: lib/rubocop/cop/performance/times_map.rb

Overview

Checks for .times.map calls. In most cases such calls can be replaced with an explicit array creation.

Examples:

# bad
9.times.map do |i|
  i.to_s
end

# good
Array.new(9) do |i|
  i.to_s
end

Cop Safety Information:

  • This cop’s autocorrection is unsafe because Integer#times does nothing if receiver is 0 or less. However, Array.new raises an error if argument is less than 0.

    For example:

    -1.times{}    # does nothing
    Array.new(-1) # ArgumentError: negative array size

Constant Summary

Instance Method Summary

Instance Method Details

#check(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/times_map.rb', line 51

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

#handleable_receiver?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/times_map.rb', line 63

def handleable_receiver?(node)
  receiver = node.receiver.receiver
  return true if receiver.literal? && (receiver.int_type? || receiver.float_type?)

  node.receiver.dot?
end

#message(map_or_collect, count) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/times_map.rb', line 70

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

#on_block(node) Also known as: #on_numblock

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/times_map.rb', line 44

def on_block(node)
  check(node)
end

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/times_map.rb', line 42

alias on_csend on_send

#on_numblock(node)

Alias for #on_block.

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/times_map.rb', line 47

alias on_numblock on_block

#on_send(node) Also known as: #on_csend

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/times_map.rb', line 39

def on_send(node)
  check(node)
end