Class: Hone::Patterns::EachWithObject

Inherits:
Base
  • Object
show all
Defined in:
lib/hone/patterns/each_with_object.rb

Overview

Pattern: inject({}) { |acc, x| ... ; acc } -> each_with_object({}) { |x, acc| }

inject/reduce with a hash or array accumulator requires returning the accumulator at the end of each block iteration. each_with_object automatically passes the same object, making the code cleaner and avoiding the need to return the accumulator.

Examples:

# Bad: must return acc at end of block
items.inject({}) { |acc, x| acc[x.id] = x; acc }
# Good: acc is automatically passed
items.each_with_object({}) { |x, acc| acc[x.id] = x }

Instance Attribute Summary

Attributes inherited from Base

#findings

Instance Method Summary collapse

Methods inherited from Base

#add_finding, inherited, #initialize, scan_file

Constructor Details

This class inherits a constructor from Hone::Patterns::Base

Instance Method Details

#visit_call_node(node) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/hone/patterns/each_with_object.rb', line 21

def visit_call_node(node)
  super

  return unless %i[inject reduce].include?(node.name)
  return unless block_attached?(node)
  return unless empty_collection_initial_value?(node)

  add_finding(
    node,
    message: "Consider using `.each_with_object(#{initial_value_literal(node)})` instead of `.#{node.name}(#{initial_value_literal(node)})` for cleaner accumulator pattern",
    speedup: "Cleaner, avoids returning accumulator each iteration"
  )
end