Class: Hone::Patterns::HashEachKey
- Defined in:
- lib/hone/patterns/hash_each_key.rb
Overview
Pattern: hash.keys.each { } -> hash.each_key { }
keys.each creates an intermediate array of keys then iterates. each_key iterates keys directly without allocation.
Also detects hash.values.each { } -> hash.each_value { }
Instance Attribute Summary
Attributes inherited from Base
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
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/hone/patterns/hash_each_key.rb', line 15 def visit_call_node(node) super # Look for: .each { } where receiver is .keys or .values return unless node.name == :each && block_attached?(node) receiver = node.receiver return unless receiver.is_a?(Prism::CallNode) case receiver.name when :keys add_finding( node, message: "Use `.each_key { }` instead of `.keys.each { }` to avoid intermediate array", speedup: "Iterates keys directly without allocating array" ) when :values add_finding( node, message: "Use `.each_value { }` instead of `.values.each { }` to avoid intermediate array", speedup: "Iterates values directly without allocating array" ) end end |