Project

General

Profile

Actions

Feature #13683

closed

Add strict Enumerable#single

Added by dnagir (Dmytrii Nagirniak) almost 7 years ago. Updated over 2 years ago.

Status:
Feedback
Assignee:
-
Target version:
-
[ruby-core:81779]

Description

Summary

This is inspired by other languages and frameworks, such as LINQ's Single (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.


Related issues 1 (1 open0 closed)

Related to Ruby master - Feature #18135: Introduce Enumerable#detect_onlyOpenActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0