[ruby-core:124564] [Ruby Feature#13683] Add strict Enumerable#single
Issue #13683 has been updated by Dan0042 (Daniel DeLorme). mame (Yusuke Endoh) wrote in #note-48:
But no one seriously considered it because we can find no use case for it.
Uh, seriously? I gave an example in #note-16 and we have 11 other similar instances in our codebase. But none that raise an error. Pretty often used as `collection.compact.uniq.single` where we use it as default value for a new record if there is only one. Or, let's say search for product "ABC" and if there is only one match then redirect to it directly, otherwise display the search results. Anyway, I'm just giving my honest feedback. If if turns out the method raises an error, it's no big deal, I'll just keep using our own #single. Eregon (Benoit Daloze) wrote in #note-50:
then `ary.first if ary.size == 1` or so is good enough.
That logic doesn't work at all. Of course it's "good enough" but in that case `raise if ary.size != 1` would also be "good enough". ---------------------------------------- Feature #13683: Add strict Enumerable#single https://bugs.ruby-lang.org/issues/13683#change-116138 * 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)
-
Dan0042 (Daniel DeLorme)