访问 Ruby (1.9) 哈希中的最后一个键值对
从 Ruby 1.9 开始,哈希保留插入顺序,这非常酷。我想知道访问最后一个键值对的最佳方式。
我已经编写了一些执行此操作的代码:
hash.values.last
这有效并且非常容易理解,但也许可以直接访问最后一个值,而不是通过中介(值数组)。是吗?
As of Ruby 1.9, hashes retain insertion order which is very cool. I want to know the best way to access the last key–value pair.
I've written some code which does this:
hash.values.last
This works and is very easy to comprehend, but perhaps it's possible to access the last value directly, rather that via an intermediary (the array of values). Is it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
哈希有一个“第一个”方法,但它返回数组模式下的第一对,最后,你可以尝试:
这返回数组模式下的最后一对,就像“第一个方法”
Hash have a "first" method, but that return the first pair in array mode, for last, you can try:
this return last pair in array mode like "first method"
我自己使用的另一种选择:
当您想直接将值分配给散列的最后一个元素时,效果更好:
One more alternative that I'm using myself:
which works out better when you want to directly assign a value onto the last element of the hash:
没有内置任何东西,没有。但如果你愿意的话,你可以猴子修补一个(当然通常不推荐):
然后:
Nothing built in, no. But you could monkey-patch one if you were so inclined (not usually recommended, of course):
And then:
我只是对一个非常大的哈希值执行此操作:
I just did this for a very large hash: