Class: Hone::Patterns::GsubToTr
- Defined in:
- lib/hone/patterns/gsub_to_tr.rb
Overview
Pattern: str.gsub('a', 'b') -> str.tr('a', 'b')
For replacing single characters, tr is optimized and faster than gsub. gsub has regex overhead even for simple string patterns.
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
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/hone/patterns/gsub_to_tr.rb', line 13 def visit_call_node(node) super return unless node.name == :gsub args = node.arguments&.arguments return unless args&.size == 2 first_arg = args[0] second_arg = args[1] # Check if both arguments are single-character strings return unless single_char_string?(first_arg) && single_char_string?(second_arg) add_finding( node, message: "Use `.tr('#{string_value(first_arg)}', '#{string_value(second_arg)}')` instead of `.gsub` for single character replacement", speedup: "tr is optimized for character translation, avoids regex overhead" ) end |