[ruby-core:121188] [Ruby master Feature#21160] Local return from proc
From:
"nobu (Nobuyoshi Nakada) via ruby-core" <ruby-core@...>
Date:
2025-02-27 02:23:13 UTC
List:
ruby-core #121188
Issue #21160 has been updated by nobu (Nobuyoshi Nakada).
Why not rescue `LocalJumpError`?
```ruby
def self.fulfill_promise(promise_name, data)
puts "Fulfilling promise: #{promise_name}"
callback = @@promise_callbacks[promise_name]
begin
complete = callback.call(data)
rescue LocalJumpError => e
complete = e.exit_value
end
if complete
puts 'Complete!'
else
puts 'Failed!'
end
end
```
This works with both of `return` and `break` in already released versions of Ruby, and even your DSL does not need to change.
If we were add a new keyword, you would have to wait for the end of this year at least.
----------------------------------------
Feature #21160: Local return from proc
https://bugs.ruby-lang.org/issues/21160#change-112123
* Author: JustJosh (Joshua Stowers)
* Status: Open
----------------------------------------
When writing DSL-style helper methods, I often store block arguments as procs to use as callbacks.
Using `return` in a proc will return from the context it was created in, which is unsuitable in the following example.
Since procs cannot be converted to lambdas, I end up using `next` to return a value from them early.
Example:
``` ruby
fulfills_promise :generate_large_image do |image_data|
next false if image_data.nil?
puts 'Saving image..'
# etc.
end
```
This works but confuses most readers.
I propose introducing an alias for it that is more appropriate for this use case.
Perhaps `pass` or `continue`?
It's worth noting that `return` would work with `fulfills_promise :foo, -> (bar) do`, though it detracts a bit from a DSL's expressiveness.
--
https://bugs.ruby-lang.org/
______________________________________________
ruby-core mailing list -- ruby-core@ml.ruby-lang.org
To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/