[#99868] [Ruby master Bug#17144] Tempfile.open { ... } does not unlink the file — eregontp@...
Issue #17144 has been reported by Eregon (Benoit Daloze).
15 messages
2020/09/03
[ruby-core:100129] [Ruby master Feature#13683] Add strict Enumerable#single
From:
mame@...
Date:
2020-09-25 07:14:41 UTC
List:
ruby-core #100129
Issue #13683 has been updated by mame (Yusuke Endoh).
A practical use case: When scraping a HTML document or something, sometimes we assume that an array length is 1.
```
nodes = html_node.children.select {|node| node.name == "table" }
raise if nodes.size == 1
the_node_i_want = nodes.first
```
The `raise` is needed for the case where my assumption is wrong.
This proposal makes it a bit helpful:
```
the_node_i_want = html_node.children.select {|node| node.name == "table" }.sole
```
----------------------------------------
Feature #13683: Add strict Enumerable#single
https://bugs.ruby-lang.org/issues/13683#change-87698
* 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:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>