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

davidchambers picture davidchambers · Oct 13, 2011 · Viewed 22.1k times · Source

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?

Answer

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"