Accessing the last key–value pair in a Ruby (1.9) hash
As of Ruby 1.9, hashes retain ins开发者_如何学运维ertion 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?
Hash have a "first" method, but that return the first pair in array mode, for last, you can try:
my_hash.to_a.last
this return last pair in array mode like "first method"
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>'
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
I just did this for a very large hash:
hash.reverse_each.with_index do |(_, value), index|
break value if (index == 0)
end
精彩评论