123456789_123456789_123456789_123456789_123456789_

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

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, AutoCorrector, Base
Instance Chain:
self, Base
Inherits: Base
  • Object
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

Cop Safety Information:

  • This cop is unsafe because it assumes that the receiver responds to #bytesize method.

Constant Summary

Instance Method Summary

Instance Method Details

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/string_bytesize.rb', line 41

alias on_csend on_send

#on_send(node) Also known as: #on_csend

[ GitHub ]

  
# 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