[ruby-core:82140] [Ruby trunk Feature#13683] Add strict Enumerable#single

From: johncbackus@...
Date: 2017-07-24 00:26:06 UTC
List: ruby-core #82140
Issue #13683 has been updated by backus (John Backus).


+1 to this proposal!! I have a `Util.one(...)` method in a half dozen or more projects. IMO `#one` is a nicer name than `#single`.

[ROM](https://github.com/rom-rb/rom/blob/6016d323ca0a2aa38167e84a4eb2da0384e75b13/core/lib/rom/relation/loaded.rb#L49-L77) exposes an interface I like when reading results from the db:

 - `#one!` - raise an error unless the result's `#size` is *exactly* `1`
 - `#one` - raise an error if the result's `#size` is greater than `1`. Return the result of `#first` otherwise (so an empty result returns `nil`).

I don't think the implementation should use the `#one?` predicate though. It would be confusing if `[nil, true, false].single` gave you `nil` instead of raising an error. 

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

* Author: dnagir (Dmytrii Nagirniak)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
### 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>

In This Thread

Prev Next