I haven't found any previous rubocop-related literature to this topic. Sorry if this is a duplicate.
In our projects, we currently have trouble due to return statements inside blocks. For example, the following will not print "after yield":
def some_method(&_block)
puts 'before yield'
yield
puts 'after yield'
end
def main
some_method do
return 2
end
end
main
Since we heavily use Rubocop for detecting bad practices, it would be supercool to have it yell at us if we write stuff like the above example: in main, instead of return 2 we should be using next 2.
Is there already a feature in Rubocop supporting this? If not, I'd like to place a feature request :-)
Returning from blocks is pretty common in Ruby-land I guess. Not sure everyone would agree it's good idea to avoid it. I myself understand your concerns, but can imagine there could be cases when return in a block might be justified.
Thank you for your feedback. Perhaps, we will write our own cop.
We've been bitten by this problem several times - in my experience when someone adds a return statement inside a block, they're always trying to return from the block, not the enclosing method.
@bbatsov even if there are legitimate cases for using return inside a block, I suspect unintentional incorrect usage vastly outnumbers them. Sometimes you might really want to rescue from Exception too, for example, but we still have a cop for that.
@eugeneius makes a good point. These days Rubocop can enforce many rules beyond the community style guide. I suspect the maintainers would accept a PR implementing this cop.
There might be a debate about whether the cop is enabled by default though. 馃槃
Most helpful comment
We've been bitten by this problem several times - in my experience when someone adds a
returnstatement inside a block, they're always trying to return from the block, not the enclosing method.@bbatsov even if there are legitimate cases for using
returninside a block, I suspect unintentional incorrect usage vastly outnumbers them. Sometimes you might really want to rescue fromExceptiontoo, for example, but we still have a cop for that.