Re: [Rails] accessing key/value pairs in views from model TYPES list

10 views
Skip to first unread message

Walter Lee Davis

unread,
Apr 25, 2017, 7:18:40 PM4/25/17
to rubyonra...@googlegroups.com

> On Apr 25, 2017, at 8:09 AM, fugee ohu <fuge...@gmail.com> wrote:
>
> I have a TYPES list in my model for ADDRESS_STATE_TYPES like ADDRESS_STATE_TYPES =
> [ ['Alabama', 'AL'], ...
> Now in my controller i have the value of address_state from the pararms list which for the first in the list would be 'AL' How can I retrieve the 'Alabama' column in my controller if I have the other value, 'AL' from params list
> Thanks in advance

Well, since you have the data in an array, you can't index into it like you could in a Hash. There you could have

{ 'AL' => 'Alabama', ... }

and then you could find by either keys or values using
name = ADDRESS_STATE_TYPES['AL']
or
code = ADDRESS_STATE_TYPES.key('Alabama').

But in an array, you're going to have to iterate to find it:

def name_for_code(code)
ADDRESS_STATE_TYPES.each do | pair |
return pair.first if pair.last == code
end
end

Walter

>
> --
> 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-ta...@googlegroups.com.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/be118090-9621-464d-8a53-0122fc8e975c%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Hassan Schroeder

unread,
Apr 25, 2017, 7:27:25 PM4/25/17
to rubyonrails-talk
On Tue, Apr 25, 2017 at 4:18 PM, Walter Lee Davis <wa...@wdstudio.com> wrote:

> But in an array, you're going to have to iterate to find it:
>
> def name_for_code(code)
> ADDRESS_STATE_TYPES.each do | pair |
> return pair.first if pair.last == code
> end
> end

or e.g.

2.3.3 (main):0 > types = [['Alabama','AL'],['California','CA']]
=> [
[0] [
[0] "Alabama",
[1] "AL"
],
[1] [
[0] "California",
[1] "CA"
]
]
2.3.3 (main):0 > types.to_h.invert.dig("CA")
=> "California"
2.3.3 (main):0 >

--
Hassan Schroeder ------------------------ hassan.s...@gmail.com
twitter: @hassan
Consulting Availability : Silicon Valley or remote

fugee ohu

unread,
Apr 25, 2017, 8:27:44 PM4/25/17
to Ruby on Rails: Talk
Thanks 

fugee ohu

unread,
Apr 25, 2017, 8:28:46 PM4/25/17
to Ruby on Rails: Talk
Thanks 
Reply all
Reply to author
Forward
0 new messages