class RuboCop::Cop::Style::RedundantBegin
end
end
baz
rescue Bar
foo
begin
-> do
# Stabby lambdas don’t support implicit ‘begin` in `do-end` blocks.
# good
end
anything
rescue => ex
something
do_something do
# In Ruby 2.5 or later, you can omit `begin` in `do-end` block.
# good
end
end
anything
rescue => ex
something
begin
do_something do
# When using Ruby 2.5 or later.
# bad
do_something
# good
end
do_something
begin
# bad
end
something
rescue StandardError => e
bala
ala
def preferred
# good
end
end
something
rescue StandardError => e
bala
ala
begin
def redundant
# bad
@example
Currently it checks for code like this:
This cop checks for redundant `begin` blocks.
def contain_rescue_or_ensure?(node)
def contain_rescue_or_ensure?(node) first_child = node.children.first first_child.rescue_type? || first_child.ensure_type? end
def on_block(node)
def on_block(node) return if target_ruby_version < 2.5 return if node.send_node.lambda_literal? return if node.braces? return unless node.body&.kwbegin_type? register_offense(node.body) end
def on_def(node)
def on_def(node) return unless node.body&.kwbegin_type? register_offense(node.body) end
def on_kwbegin(node)
def on_kwbegin(node) return if contain_rescue_or_ensure?(node) || valid_context_using_only_begin?(node) register_offense(node) end
def register_offense(node)
def register_offense(node) add_offense(node.loc.begin) do |corrector| corrector.remove(node.loc.begin) corrector.remove(node.loc.end) end end
def valid_context_using_only_begin?(node)
def valid_context_using_only_begin?(node) parent = node.parent node.each_ancestor.any?(&:assignment?) || parent&.post_condition_loop? || parent&.send_type? || parent&.operator_keyword? end