Class: RuboCop::Cop::Performance::CollectionLiteralInLoop
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Performance::CollectionLiteralInLoop
- Defined in:
- lib/rubocop/cop/performance/collection_literal_in_loop.rb
Overview
Identifies places where Array and Hash literals are used within loops. It is better to extract them into a local variable or constant to avoid unnecessary allocations on each iteration.
You can set the minimum number of elements to consider an offense with ‘MinSize`.
Constant Summary collapse
- MSG =
'Avoid immutable %<literal_class>s literals in loops. ' \ 'It is better to extract it into a local variable or a constant.'
- POST_CONDITION_LOOP_TYPES =
%i[while_post until_post].freeze
- LOOP_TYPES =
(POST_CONDITION_LOOP_TYPES + %i[while until for]).freeze
- ENUMERABLE_METHOD_NAMES =
(Enumerable.instance_methods + [:each]).to_set.freeze
- NONMUTATING_ARRAY_METHODS =
%i[& * + - <=> == [] all? any? assoc at bsearch bsearch_index collect combination compact count cycle deconstruct difference dig drop drop_while each each_index empty? eql? fetch filter find_index first flatten hash include? index inspect intersection join last length map max min minmax none? one? pack permutation product rassoc reject repeated_combination repeated_permutation reverse reverse_each rindex rotate sample select shuffle size slice sort sum take take_while to_a to_ary to_h to_s transpose union uniq values_at zip |].freeze
- ARRAY_METHODS =
(ENUMERABLE_METHOD_NAMES | NONMUTATING_ARRAY_METHODS).to_set.freeze
- NONMUTATING_HASH_METHODS =
%i[< <= == > >= [] any? assoc compact dig each each_key each_pair each_value empty? eql? fetch fetch_values filter flatten has_key? has_value? hash include? inspect invert key key? keys? length member? merge rassoc rehash reject select size slice to_a to_h to_hash to_proc to_s transform_keys transform_values value? values values_at].freeze
- HASH_METHODS =
(ENUMERABLE_METHOD_NAMES | NONMUTATING_HASH_METHODS).to_set.freeze
Instance Method Summary collapse
Instance Method Details
#on_send(node) ⇒ Object
80 81 82 83 84 85 86 |
# File 'lib/rubocop/cop/performance/collection_literal_in_loop.rb', line 80 def on_send(node) receiver, method, = *node.children return unless check_literal?(receiver, method) && parent_is_loop?(receiver) = format(MSG, literal_class: literal_class(receiver)) add_offense(receiver, message: ) end |