Class: Hone::Patterns::StringStartWith

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

Overview

Pattern: str == 'x' or str.match?(/^x/) -> str.start_with?('x')

Indexing at position 0 for comparison or using regex with ^ anchor is less clear and potentially slower than using start_with?.

Examples:

Bad

str[0] == 'x'
str.match?(/^foo/)

Good

str.start_with?('x')
str.start_with?('foo')

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
34
35
36
37
# File 'lib/hone/patterns/string_start_with.rb', line 21

def visit_call_node(node)
  super

  if index_zero_comparison?(node)
    add_finding(
      node,
      message: "Use `start_with?` instead of `str[0] == ...` for cleaner code",
      speedup: "Cleaner and avoids substring/regex overhead"
    )
  elsif regex_start_anchor?(node)
    add_finding(
      node,
      message: "Use `start_with?` instead of `match?(/^.../)` to avoid regex overhead",
      speedup: "Cleaner and avoids substring/regex overhead"
    )
  end
end