class RuboCop::Cop::Performance::FixedSize

Do not compute the size of statically sized objects.

@example

# String methods
# bad
'foo'.size
%q[bar].count
%(qux).length

# Symbol methods
# bad
:fred.size
:'baz'.length

# Array methods
# bad
[1, 2, thud].count
%W(1, 2, bar).size

# Hash methods
# bad
{ a: corge, b: grault }.length

# good
foo.size
bar.count
qux.length

# good
:"#{fred}".size
CONST = :baz.length

# good
[1, 2, *thud].count
garply = [1, 2, 3]
garply.size

# good
{ a: corge, **grault }.length
waldo = { a: corge, b: grault }
waldo.size

Constants

MSG

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/performance/fixed_size.rb, line 55
def on_send(node)
  return if node.ancestors.any? { |ancestor| allowed_parent?(ancestor) }

  counter(node) do |var, arg|
    return if allowed_variable?(var) || allowed_argument?(arg)

    add_offense(node)
  end
end

Private Instance Methods

allowed_argument?(arg) click to toggle source
# File lib/rubocop/cop/performance/fixed_size.rb, line 71
def allowed_argument?(arg)
  arg && non_string_argument?(arg.first)
end
allowed_parent?(node) click to toggle source
# File lib/rubocop/cop/performance/fixed_size.rb, line 75
def allowed_parent?(node)
  node && (node.casgn_type? || node.block_type?)
end
allowed_variable?(var) click to toggle source
# File lib/rubocop/cop/performance/fixed_size.rb, line 67
def allowed_variable?(var)
  contains_splat?(var) || contains_double_splat?(var)
end
contains_double_splat?(node) click to toggle source
# File lib/rubocop/cop/performance/fixed_size.rb, line 85
def contains_double_splat?(node)
  return unless node.hash_type?

  node.each_child_node(:kwsplat).any?
end
contains_splat?(node) click to toggle source
# File lib/rubocop/cop/performance/fixed_size.rb, line 79
def contains_splat?(node)
  return unless node.array_type?

  node.each_child_node(:splat).any?
end
non_string_argument?(node) click to toggle source
# File lib/rubocop/cop/performance/fixed_size.rb, line 91
def non_string_argument?(node)
  node && !node.str_type?
end