Ruby on Rails Tuesday, May 15, 2018

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

> On May 15, 2018, at 1:10 PM, fugee ohu <fugee279@gmail.com> wrote:
>
> 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
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
> To post to this group, send email to rubyonrails-talk@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/d7eea706-b4fa-4413-82e3-fda20742fb32%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/C870649E-8F80-414B-B671-C21B1E460C4F%40wdstudio.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment