class RuboCop::Cop::Performance::ChainArrayAllocation
This cop is used to identify usages of @example
# bad array = ["a", "b", "c"] array.compact.flatten.map { |x| x.downcase }
Each of these methods (`compact`, `flatten`, `map`) will generate a new intermediate array that is promptly thrown away. Instead it is faster to mutate when we know it's safe.
@example
# good. array = ["a", "b", "c"] array.compact! array.flatten! array.map! { |x| x.downcase } array
Constants
- ALWAYS_RETURNS_NEW_ARRAY
These methods ALWAYS return a new array after they're called it's safe to mutate the the resulting array
- HAS_MUTATION_ALTERNATIVE
These methods have a mutation alternative. For example :collect can be called as :collect!
- MSG
- RETURNS_NEW_ARRAY_WHEN_NO_BLOCK
These methods return a new array only when called without a block.
- RETURN_NEW_ARRAY_WHEN_ARGS
These methods return a new array but only sometimes. They must be called with an argument. For example:
[1,2].first # => 1 [1,2].first(1) # => [1]
Public Instance Methods
on_send(node)
click to toggle source
# File lib/rubocop/cop/performance/chain_array_allocation.rb, line 62 def on_send(node) flat_map_candidate?(node) do |fm, sm, _| range = range_between( node.loc.dot.begin_pos, node.source_range.end_pos ) add_offense( node, location: range, message: format(MSG, method: fm, second_method: sm) ) end end