# Looking up a hash in an array

**URL:** <https://www.ruby-forum.com/t/looking-up-a-hash-in-an-array/107050>\
**Category:** Rails\
**Created:** [June 17, 2007, 10:52am UTC](https://www.ruby-forum.com/t/looking-up-a-hash-in-an-array/107050 "2007-06-17T10:52:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![partydrone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a6a055/32.png) [@partydrone](https://www.ruby-forum.com/u/partydrone)\
**Post date:** [June 17, 2007, 10:52am UTC](https://www.ruby-forum.com/t/looking-up-a-hash-in-an-array/107050/1 "2007-06-17T10:52:48Z")

</div>

I have created a STATES constant in my application-an array of hashes:

STATES = [  
{‘code’ =\> ‘AL’, ‘name’ =\> ‘Alabama’},  
{‘code’ =\> ‘AK’, ‘name’ =\> ‘Alaska’},  
{‘code’ =\> ‘AZ’, ‘name’ =\> ‘Arizona’},  
{‘code’ =\> ‘AR’, ‘name’ =\> ‘Arkansas’},  
{‘code’ =\> ‘CA’, ‘name’ =\> ‘California’},  
etc.  
]

I’m storing the state code in the database with an object (i.e.,  
event, address, etc.) When I retrieve, say, an Event from the  
database, I want to use the code ‘AZ’ to look up the name ‘Arizona’  
and display it.

I don’t seem to be able to get my head around how to accomplish this.  
Maybe it’s because it’s late and I’m really tired…

---

<div class="post-metadata">

**Author:** ![partydrone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a6a055/32.png) [@partydrone](https://www.ruby-forum.com/u/partydrone)\
**Post date:** [June 17, 2007, 11:49am UTC](https://www.ruby-forum.com/t/looking-up-a-hash-in-an-array/107050/2 "2007-06-17T11:49:52Z")

</div>

> > STATES.find{ |state| state[“code”] == “AL” }[“name”]  
> > =\> “Alabama”

---

<div class="post-metadata">

**Author:** ![partydrone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a6a055/32.png) [@partydrone](https://www.ruby-forum.com/u/partydrone)\
**Post date:** [June 17, 2007, 4:05pm UTC](https://www.ruby-forum.com/t/looking-up-a-hash-in-an-array/107050/3 "2007-06-17T16:05:23Z")

</div>

The way you currently have your codes setup you can not locate  
anything by state code.

Just use a hash as follows:

states = {‘AL’ =\> ‘Alabama’, ‘AK’ =\> ‘Alaska’, …

then you can locate the name by states[code].

Michael
