Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first item out of a Ruby array in a hash

Tags:

ruby

I have a Ruby hash that looks like this:

h = {"side1"=>["green", "Green"], "side2"=>["verde", "Verde"]}

How can I get the first (or last) item at a particular key in the hash?

like image 496
Andrew Avatar asked Aug 05 '11 05:08

Andrew


1 Answers

I ran into a similar situation where I arbitrarily wanted the "first" entry from the hash for some test code. That's not exactly what this question is about, but it came up in the search I ran so figure it might do likewise for others.

Of course "first item" is arbitrary in a hash, but the keys method will return a list of all keys sorted by some magic. If you like that sort order, then you can get the "first" method with

h[h.keys.first]
like image 123
Zymurge Avatar answered Sep 21 '22 05:09

Zymurge