[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-core
Subject:    [ruby-core:105074] [Ruby master Bug#18135] Introduce Enumerable#detect_only
From:       "meisel (Michael Eisel)" <noreply () ruby-lang ! org>
Date:       2021-08-26 19:18:26
Message-ID: redmine.issue-18135.20210826191826.51725 () ruby-lang ! org
[Download RAW message or body]

Issue #18135 has been reported by meisel (Michael Eisel).

----------------------------------------
Bug #18135: Introduce Enumerable#detect_only
https://bugs.ruby-lang.org/issues/18135

* Author: meisel (Michael Eisel)
* Status: Open
* Priority: Normal
* Backport: 2.6: UNKNOWN, 2.7: UNKNOWN, 3.0: UNKNOWN
----------------------------------------
It can be important to get the only element for which a block returns true, and to \
assert that this is the only element as such. For example, this can be a very helpful \
sanity check when one is working with data that's outside of their control and is not \
perfectly understood. They may have a guess as to how to get a specific element \
matching some criteria, but if they used Enumerable#detect might be hiding the fact \
that they have written an incorrect block and that there's in fact more than one \
element that matches it. It could also be a parameter on Typically, I'd do it like \
this:

```
matches = array.select { |elem| some_method(elem) }
raise if matches.size != 0
match = matches.first
```
Here, it would be shortened to:
```
match = array.detect_only { |elem| some_method(elem) }
```

It could also be a parameter on Enumerable#detect instead of a separate method.



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic