Class: RuboCop::Cop::Style::For

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ConfigurableEnforcedStyle
Defined in:
lib/rubocop/cop/style/for.rb

Overview

Looks for uses of the ‘for` keyword or `each` method. The preferred alternative is set in the EnforcedStyle configuration parameter. An `each` call with a block on a single line is always allowed.

Examples:

EnforcedStyle: each (default)

# bad
def foo
  for n in [1, 2, 3] do
    puts n
  end
end

# good
def foo
  [1, 2, 3].each do |n|
    puts n
  end
end

EnforcedStyle: for

# bad
def foo
  [1, 2, 3].each do |n|
    puts n
  end
end

# good
def foo
  for n in [1, 2, 3] do
    puts n
  end
end

Constant Summary collapse

EACH_LENGTH =
'each'.length
PREFER_EACH =
'Prefer `each` over `for`.'
PREFER_FOR =
'Prefer `for` over `each`.'

Instance Method Summary collapse

Methods included from AutoCorrector

support_autocorrect?

Methods included from ConfigurableEnforcedStyle

#alternative_style, #alternative_styles, #ambiguous_style_detected, #correct_style_detected, #detected_style, #detected_style=, #no_acceptable_style!, #no_acceptable_style?, #opposite_style_detected, #style, #style_configured?, #style_detected, #style_parameter_name, #supported_styles, #unexpected_style_detected

Instance Method Details

#on_block(node) ⇒ Object Also known as: on_numblock



64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/rubocop/cop/style/for.rb', line 64

def on_block(node)
  return unless suspect_enumerable?(node)

  if style == :for
    return unless node.receiver

    add_offense(node, message: PREFER_FOR) do |corrector|
      EachToForCorrector.new(node).call(corrector)
      opposite_style_detected
    end
  else
    correct_style_detected
  end
end

#on_for(node) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/rubocop/cop/style/for.rb', line 53

def on_for(node)
  if style == :each
    add_offense(node, message: PREFER_EACH) do |corrector|
      ForToEachCorrector.new(node).call(corrector)
      opposite_style_detected
    end
  else
    correct_style_detected
  end
end