我解决了一个问题,它需要取散列的最后一个键值对。例子:
hash = { "aa" => { :count => 1, :width => 333 }, "bb" => { :count => 1, :width => 77 } }
Run Code Online (Sandbox Code Playgroud)
我需要结果
result = [ "bb" => { :count => 1, :width => 77 } ]
Run Code Online (Sandbox Code Playgroud)
哈希有第一种方法
hash.first
=> [ "aa" => { :count => 1, :width => 333 } ]
Run Code Online (Sandbox Code Playgroud)
我想使用该last方法,但出现错误
NoMethodError: undefined method `last' for #<Hash:0x00007f82c75a9988>
from (pry):19:in `__pry__'
Run Code Online (Sandbox Code Playgroud)
这是我的解决方案
result = [hash.stringify_keys.keys[1], hash.stringify_keys.values[1]]
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么 Ruby 哈希没有最后一种方法。
firstruby 哈希的方法来自Enumerable。它没有方法last,所以Hash也没有。
如果我猜测,Enumerable出于效率原因没有它。由于Enumerable只需要该方法each起作用,因此确定最后一个元素将需要完全遍历序列(可能是无限长的)。
并且Hash没有它,因为键值映射在概念上不是有序的数据结构。