Class: RuboCop::Cop::Performance::StringBytesize

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/performance/string_bytesize.rb

Overview

Checks for calls to ‘#bytes` counting method and suggests using `bytesize` instead. The `bytesize` method is more efficient and directly returns the size in bytes, avoiding the intermediate array allocation that `bytes.size` incurs.

Examples:

# bad
string_var.bytes.count
"foobar".bytes.size

# good
string_var.bytesize
"foobar".bytesize

Constant Summary collapse

MSG =
'Use `String#bytesize` instead of calculating the size of the bytes array.'
RESTRICT_ON_SEND =
%i[size length count].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



32
33
34
35
36
37
38
39
40
# File 'lib/rubocop/cop/performance/string_bytesize.rb', line 32

def on_send(node)
  string_bytes_method?(node) do
    range = node.receiver.loc.selector.begin.join(node.source_range.end)

    add_offense(range) do |corrector|
      corrector.replace(range, 'bytesize')
    end
  end
end