Forum: Ruby on Rails Looking up a hash in an array

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
partydrone (Guest)
on 2007-06-17 12:52
(Received via mailing list)
I have created a STATES constant in my application-an array of hashes:

  {'code' => 'AL', 'name' => 'Alabama'},
  {'code' => 'AK', 'name' => 'Alaska'},
  {'code' => 'AZ', 'name' => 'Arizona'},
  {'code' => 'AR', 'name' => 'Arkansas'},
  {'code' => 'CA', 'name' => 'California'},

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...
Grant H. (Guest)
on 2007-06-17 13:49
(Received via mailing list)
>> STATES.find{ |state| state["code"] == "AL" }["name"]
=> "Alabama"
MichaelLatta (Guest)
on 2007-06-17 18:05
(Received via mailing list)
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].

This topic is locked and can not be replied to.