Feature #21822
closedExpose Return Value in the ensure Block
Description
I'd like to propose a simple feature that allows easy access to the return value inside an ensure block.
begin
# ...
ensure => ret
# ret is nil if an exception is raised
LOGGER.debug "return value: #{ret}"
end
Updated by mame (Yusuke Endoh) 2 months ago
- Related to Feature #18083: Capture error in ensure block. added
Updated by nobu (Nobuyoshi Nakada) 2 months ago
Is the variable nil if an exception is raised, even for non-local variable?
By analogy with rescue, it feels natural for me that the variable is unchanged in that case.
Updated by matz (Yukihiro Matsumoto) about 1 month ago
I don't think it's not worth for the new syntax, where you can do similar thing with:
begin
ret = begin
# ....
end
ensure
LOGGER.debug "return value: #{ret}"
end
Matz.
Updated by artemb (Artem Borodkin) about 1 month ago
begin ret = begin # .... end ensure LOGGER.debug "return value: #{ret}" end
For me, ensure => ret looks cleaner, reduces cognitive overhead, and is simply easier on the eyes when reviewing real code.
The structure is easier to parse visually, and the intent is clearer compared to the alternatives.
Also, it doesn’t break any existing behavior — it’s purely additive, just a small but useful extension that makes the code more elegant and pleasant to read.
Updated by matz (Yukihiro Matsumoto) 2 days ago
- Status changed from Open to Rejected
Thank you for the feedback. I understand the aesthetic appeal, but "cleaner" is subjective, and the existing pattern is already idiomatic Ruby with no real cognitive overhead.
More importantly, "purely additive" does not mean cost-free. Every new syntax must be defined precisely, documented, and handle edge cases correctly. As nobu noted in #3, the semantics when an exception is raised are not obvious, which suggests the concept has rough edges that outweigh the cosmetic benefit.
Matz.