-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enumerable
method to find the first truthy block result and return that result
#14879
Comments
To be clear, I'm not attached to the |
response = Response.new([Choice.new(Message.new(nil)), Choice.new(Message.new([ToolCall.new, ToolCall.new]))])
if tool_calls = response.choices.each { |c| tc = c.message.tool_calls; break tc if tc }
pp tool_calls # => [ToolCall(), ToolCall()]
end This is best I could come up with without introducing something new. As reference only. |
It is still slightly clunky, but at least it doesn't involve break:
If it is fine to find the first not-nil-value, then |
Ruby doesn't have it, but in Elixir it is called |
Sounds good to me. I'd prefer the name |
In this comment, @Sija brought up an interesting point I hadn't considered. I normally use this for Part of me wants to push back against it because I don't know of any other |
Elixir's |
I would argue this method should have the same semantics as |
Feature Request
Is your feature request related to a problem? Please describe clearly and concisely what is it.
I have a frequent need for something that is similar to
Enumerable#find
, but rather than returning the element for which the block is truthy, it returns that truthy block result itself.This comes up when I have an array of objects that may or may not have a property set. The most recent need for this came up when implementing tool use for LLM APIs. The API response has an array of
choices
, each with amessage
, and those messages may or may not have atool_calls
array.Describe the feature you would like, optionally illustrated by examples, and how it will solve the above problem.
What I've been using in my code to make this more expressive is a monkeypatch on
Enumerable
calledfind_first
:Describe considered alternative solutions, and the reasons why you have not proposed them as a solution here.
Currently, as far as I can tell, at least, the only ways to do this involve either executing that same criteria again:
Or this format with the block expanded
These are both a lot more verbose, especially when there are multiple layers of these arrays. Having a method that returns the truthy value lets us use the shorthand block syntax and have a single expression that does all of these things smoothly.
Does it break backward compatibility, if yes then what's the migration path?
Nope. Purely additive.
The text was updated successfully, but these errors were encountered: