From: daniel@...42.com
Date: 2020-08-29T11:11:12+00:00
Subject: [ruby-core:99768] [Ruby master Feature#13683] Add strict	Enumerable#single

Issue #13683 has been updated by Dan0042 (Daniel DeLorme).


> If collection is empty and a block was given, returns the block's return value:

I really think the block form should be like find/select

```ruby
[1,2,3].one{ _1.even? }        #=> 2
[1,2,3,4].one{ _1.even? }      #=> error
[1,2,3,4].one(nil){ _1.even? } #=> nil
```

> Having `Enumerable#find` take an optional keyword argument, say `exception:`, would make more sense, be useful, and have more generality.

I don't think so; find only returns the first element found. An argument that makes it continue searching and return an exception if it finds a second match... that alters the fundamental behavior too much imho.

----------------------------------------
Feature #13683: Add strict Enumerable#single
https://bugs.ruby-lang.org/issues/13683#change-87280

* Author: dnagir (Dmytrii Nagirniak)
* Status: Feedback
* Priority: Normal
----------------------------------------
### Summary

This is inspired by other languages and frameworks, such as LINQ's [Single](https://msdn.microsoft.com/en-us/library/bb155325%28v=vs.110%29.aspx) (pardon MSDN reference), which has very big distinction between `first` and `single` element of a
collection.

- `first` normally returns the top element, and the developer assumes
  there could be many;
- `single` returns one and only one element, and it is an error if there
  are none or more than one.

We, in Ruby world, very often write `fetch_by('something').first`
assuming there's only one element that can be returned there.

But in majority of the cases, we really want a `single` element.

The problems with using `first` in this case:

- developer needs to explicitly double check the result isn't `nil`
- in case of corrupted data (more than one item returned), it will never
  be noticed

`Enumerable#single` addresses those problems in a very strong and
specific way that may save the world by simply switching from `first` to
`single`.

### Other information

- we may come with a better internal implementation (than `self.map`)
- better name could be used, maybe `only` is better, or a bang version?
- re-consider the "block" implementation in favour of a separate method (`single!`, `single_or { 'default' }`)


The original implementation is on the ActiveSupport https://github.com/rails/rails/pull/26206
But it was suggested to discuss the possibility of adding it to Ruby which would be amazing.



-- 
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>