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
|
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.
Constant Summary
-
MESSAGE =
# File 'lib/rubocop/cop/performance/times_map.rb', line 35'Use `Array.new(%<count>s)` with a block instead of `.times.%<map_or_collect>s`'
-
MESSAGE_ONLY_IF =
# File 'lib/rubocop/cop/performance/times_map.rb', line 36'only if `%<count>s` is always 0 or more'
-
RESTRICT_ON_SEND =
# File 'lib/rubocop/cop/performance/times_map.rb', line 37%i[map collect].freeze
Instance Method Summary
- #on_block(node) (also: #on_numblock)
-
#on_csend(node)
Alias for #on_send.
-
#on_numblock(node)
Alias for #on_block.
- #on_send(node) (also: #on_csend)
- #check(node) private
- #handleable_receiver?(node) ⇒ Boolean private
- #message(map_or_collect, count) private
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: (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)
# 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 (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.
# File 'lib/rubocop/cop/performance/times_map.rb', line 42
alias on_csend on_send
#on_numblock(node)
Alias for #on_block.
# 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