访问 Ruby (1.9) 哈希中的最后一个键值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7749131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:22:33  来源:igfitidea点击:

Accessing the last key–value pair in a Ruby (1.9) hash

rubyhashkey-value

提问by davidchambers

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.

从 Ruby 1.9 开始,哈希保留插入顺序,这非常酷。我想知道访问最后一个键值对的最佳方式。

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?

这很有效并且很容易理解,但也许可以直接访问最后一个值,而不是通过中介(值数组)。是吗?

采纳答案by Ben Lee

Nothing built in, no. But you could monkey-patch one if you were so inclined (not usually recommended, of course):

没有内置,没有。但是如果你愿意的话,你可以打一个猴子补丁(当然,通常不推荐):

class Hash
  def last_value
    values.last
  end
end

And then:

进而:

hash.last_value

回答by Daniel Antonio Nu?ez Carhuayo

Hash have a "first" method, but that return the first pair in array mode, for last, you can try:

Hash 有一个“first”方法,但它以数组模式返回第一对,最后,您可以尝试:

my_hash.to_a.last

this return last pair in array mode like "first method"

这在数组模式中返回最后一对,如“第一种方法”

回答by sjagr

One more alternative that I'm using myself:

我自己使用的另一种选择:

hash[hash.keys.last]

which works out better when you want to directly assign a value onto the last element of the hash:

当您想直接为散列的最后一个元素分配一个值时,效果会更好:

2.4.1 :001 > hash = {foo: 'bar'}
 => {:foo=>"bar"} 
2.4.1 :002 > hash[hash.keys.last] = 'baz'
 => "baz" 
2.4.1 :003 > hash.values.last = 'bar'
NoMethodError: undefined method `last=' for ["baz"]:Array
Did you mean?  last
    from (irb):3
    from /home/schuylr/.rvm/rubies/ruby-2.4.1/bin/irb:11:in `<main>'

回答by SHS

I just did this for a very large hash:

我只是为一个非常大的哈希做了这个:

hash.reverse_each.with_index do |(_, value), index|
  break value if (index == 0)
end