class RuboCop::Cop::Lint::TopLevelReturnWithArgument

Checks for top level return with arguments. If there is a top-level return statement with an argument, then the argument is always ignored. This is detected automatically since Ruby 2.7.

@example

# bad
return 1

# good
return

Constants

MSG

Public Instance Methods

on_return(return_node) click to toggle source
# File lib/rubocop/cop/lint/top_level_return_with_argument.rb, line 21
def on_return(return_node)
  return unless top_level_return_with_any_argument?(return_node)

  add_offense(return_node) do |corrector|
    remove_arguments(corrector, return_node)
  end
end

Private Instance Methods

remove_arguments(corrector, return_node) click to toggle source
# File lib/rubocop/cop/lint/top_level_return_with_argument.rb, line 35
def remove_arguments(corrector, return_node)
  corrector.replace(return_node, 'return')
end
top_level_return?(return_node) click to toggle source

This cop works by validating the ancestors of the return node. A top-level return node’s ancestors should not be of block, def, or defs type.

# File lib/rubocop/cop/lint/top_level_return_with_argument.rb, line 42
def top_level_return?(return_node)
  return_node.each_ancestor(:block, :def, :defs).none?
end
top_level_return_with_any_argument?(return_node) click to toggle source
# File lib/rubocop/cop/lint/top_level_return_with_argument.rb, line 31
def top_level_return_with_any_argument?(return_node)
  top_level_return?(return_node) && return_node.arguments?
end