Class: Hone::Patterns::StringCharsEach

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

Overview

Detects str.chars.each { } which should be str.each_char { }

chars.each creates an intermediate array of single-character strings. each_char iterates directly without allocation.

Examples:

Bad

str.chars.each { |c| puts c }

Good

str.each_char { |c| puts c }

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



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

def visit_call_node(node)
  if chained_chars_each?(node)
    replacement = suggest_replacement(node)
    add_finding(
      node,
      message: "Use `#{replacement}` instead of `chars.each` to avoid intermediate array allocation",
      speedup: "No intermediate array allocation"
    )
  end

  super
end