[ruby-core:96340] [Ruby master Misc#16436] hash missing #last method, make it not so consistent (it has first)
From:
zverok.offline@...
Date:
2019-12-19 16:27:28 UTC
List:
ruby-core #96340
Issue #16436 has been updated by zverok (Victor Shepelev).
`Hash` doesn't have `#first` either :)
```ruby
Hash.instance_method(:first)
# => #<UnboundMethod: Hash(Enumerable)#first(*)>
# ^^^^^^^^^^
```
The `first` method existence is just because of hash being a `Enumerable`, not because "first pair(s) of hash" seen as having some frequently used meaning.
(As a side note, Ruby probably could've had `BidirectionalEnumerable` for collections which can be enumerated both directions without side-effects; this one would be a good place to have `#last` method.)
----------------------------------------
Misc #16436: hash missing #last method, make it not so consistent (it has first)
https://bugs.ruby-lang.org/issues/16436#change-83248
* Author: zw963 (Wei Zheng)
* Status: Open
* Priority: Normal
* Assignee:
----------------------------------------
``` ruby
(pry):main(0)> h = {x:1, y:2, z:3}
{
:x => 1,
:y => 2,
:z => 3
}
(pry):main(0)> h.first
[
:x,
1
]
(pry):main(0)> h.first.first
:x
(pry):main(0)> h.first.last
1
```
last method not exist.
```ruby
(pry):main(0)> h.last
Exception: NoMethodError: undefined method `last' for {:x=>1, :y=>2, :z=>3}:Hash
```
We have to use #to_a to make last working.
```ruby
(pry):main(0)> h.to_a.last
[
:z,
3
]
(pry):main(0)> h.to_a.last.first
:z
(pry):main(0)> h.to_a.last.last
3
```
--
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>