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?
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>'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With