[ruby-core:124442] [Ruby Feature#13683] Add strict Enumerable#single
Issue #13683 has been updated by headius (Charles Nutter). zverok (Victor Shepelev) wrote in #note-39:
How about #one! or similar to indicate it must be one element?
I think Ruby's core agreement is `!` indicates the methods that change the receiver (`strip`/`strip!`), so unless we plan to introduce Rails-y agreement with it designating "dangerous" method (`save`/`save!`), this wouldn't be appropriate.
Ruby also uses it other places, like `exit!` and `kill!`, OpenSSL's `generate_key!`, Date's `new!`. It's also in English a way to emphasize the previous statement... so "one!" meaning "one and only one!".
I also feel weird about "sole" (I rarely see this word used anywhere in APIs or "simplified" engineering English), but so far, considering Matz vetoed `single` and `only`, and there are counter-arguments for `one`, this seems like the strongest contender.
I could perhaps be convinced about "solitary" or other accepted terms for "one and only one" but "sole" does not feel right at all. ---------------------------------------- Feature #13683: Add strict Enumerable#single https://bugs.ruby-lang.org/issues/13683#change-115991 * Author: dnagir (Dmytrii Nagirniak) * Status: Feedback ---------------------------------------- ### 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/
participants (1)
-
headius (Charles Nutter)