Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 711
davidchambers Avatar asked Sep 06 '25 12:09

davidchambers


2 Answers

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"

like image 194
Daniel Antonio Nuñez Carhuayo Avatar answered Sep 08 '25 02:09

Daniel Antonio Nuñez Carhuayo


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>'
like image 33
sjagr Avatar answered Sep 08 '25 02:09

sjagr