lookups in array

I have an array of US States that looks like STATE_TYPES = [ [‘Alabama’, ‘AL’], … ]
In views I need to display the State name from the value I have in the database, it’s abbreviation

If you can put those into a hash, then you can look up values by their keys, or vice-versa. Just call STATE_TYPES.to_h and then you have a hash where the names are the keys, and the abbreviations are the values. If you call STATE_TYPES.map(&:reverse).to_h, you will have the abbreviations as keys and the names as values. In either case, you could then use index notation to get a given key's value:

STATE_TYPES.to_h['Arizona']
=> 'AZ'

STATE_TYPES.map(&:reverse).to_h['AZ']
=> 'Arizona'

You don't need to call map or to_h every time, just make a new constant and use it over and over:

STATES = STATE_TYPE.map(&:reverse).to_h

STATES['AZ']
=> 'Arizona'

Walter

If you can put those into a hash, then you can look up values by their keys, or vice-versa. Just call STATE_TYPES.to_h and then you have a hash where the names are the keys, and the abbreviations are the values. If you call STATE_TYPES.map(&:reverse).to_h, you will have the abbreviations as keys and the names as values. In either case, you could then use index notation to get a given key’s value:

STATE_TYPES.to_h[‘Arizona’]
=> ‘AZ’

STATE_TYPES.map(&:reverse).to_h[‘AZ’]
=> ‘Arizona’

You don’t need to call map or to_h every time, just make a new constant and use it over and over:

STATES = STATE_TYPE.map(&:reverse).to_h

STATES[‘AZ’]
=> ‘Arizona’

Walter

Or you can take advantage of some other Ruby behavior:

The Hash[] constructor which will build a Hash from an Array of pairs (i.e., Arrays of two elements)

Hash#invert which returns a new hash with the values and keys swapped.

[3] pry(main)> STATE_TYPES = [ [‘Alabama’,‘AL’], [‘Arizona’,‘AZ’], [‘Ohio’,‘OH’] ]

=> [[“Alabama”, “AL”], [“Arizona”, “AZ”], [“Ohio”, “OH”]]

[4] pry(main)> Hash[STATE_TYPES].invert

=> {“AL”=>“Alabama”, “AZ”=>“Arizona”, “OH”=>“Ohio”}

[5] pry(main)> Hash[STATE_TYPES].invert[‘OH’]

=> “Ohio”

You might also want to look up Array#assoc and Array#rassoc which will operate directly on your array of pairs:

[6] pry(main)> STATE_TYPES.rassoc(‘OH’)

=> [“Ohio”, “OH”]

[7] pry(main)> STATE_TYPES.rassoc(‘OH’).first

=> “Ohio”

-Rob