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.
829f2eef24c244ea33165adde8bd36d5?d=identicon&s=25 partydrone (Guest)
on 2007-06-17 10: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...
602f1b8ccf99dc47c43da83d53b4ffd5?d=identicon&s=25 Grant Hutchins (Guest)
on 2007-06-17 11:49
(Received via mailing list)
>> STATES.find{ |state| state["code"] == "AL" }["name"]
=> "Alabama"
588ab1c0a5610a7e160a3b101abb91e6?d=identicon&s=25 MichaelLatta (Guest)
on 2007-06-17 16: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.