1

I have a two dimensional array that looks like this:

TITLETYPE = [['Prof.', '4'],
  ['Dr.', '3'],
  ['Mrs.', '2'],
  ['Ms.', '1'],
  ['Mr.', '0']]

I need to get the key for value 1 for example (which should be 'Ms.') How should I go about doing that?

2
  • 1
    Do you want to get the key, based on the value? Or are you just trying to access the key directly? Commented Apr 20, 2012 at 21:12
  • 2
    This is not a dictionary or anything related to key-value-pairs, it's an array of arrays. Commented Apr 20, 2012 at 21:13

4 Answers 4

8
TITLETYPE.select{ |x| x[1] == '1' }.first.first

How this works

You can use Array's select method to find the row you're looking for. Your rows ar arrays with two elements each (element 0 and element 1), so you need to look for the row in which the second element (element 1) is equal to the value you're looking for (which is the string "1"):

TITLETYPE.select{ |x| x[1] == "1" }

This will return an array with only one row:

[["Ms.", "1"]]

To get the first and only value from that array, use Array's first method, which will return:

["Ms.", "1"]

Then, from that, obtain the first value from the two values with first again:

"Ms."
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the prompt reply! Sorry i should have been more clear: i am getting the value '1' from the database, and i need to find it's corresponding value in the array (or whatever it is, what is it btw?)
3

Actually, sounds like Array#rassoc is perfect for you.

TITLETYPE.rassoc('1')[0] # => 'Ms.'

See the documentation at Ruby-doc.

Comments

0

More naturally, you should keep such information as a hash. If you often want key-to value, and key-to value is unique, then create a hash:

TYTLETYPEHASH = Hash[TYTLETYPE.map(&:reverse)]

and access it:

TYTLETYPEHASH['1'] # => 'Ms.' 

or create a hash like:

TYTLETYPEHASH = Hash[TYTLETYPE]

and access it:

TYTLEHASH.key('1') # => 'Ms.' 

Comments

0

I had a similar issue, and resolved it by simply using something like this:

<% Array.each do |value| %>

and accessing each element using <%= value[:keyname] %>

i.e.

An array which looks like this (using .inspect)

  [{:id=>1, :title=>"ABC"}, {:id=>2, :title=>"XYZ"}]

can become a HTML selection/dropdown box with:

 <select name="ClassName[TargetParameter]">
    <% Array.each do |value| %>
      <option value="<%= value[:id] %>"><%= value[:title] %></option>
    <% end %>
 </select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.