bobomoreno
bobomoreno

Reputation: 2858

Ruby array of two dimensional arrays, search/lookup?

This may be very simple, but I don't know all of Ruby's array functions.

If I have a given array like:

values = [["a", 1], ["b", 3], ["c", 7], ... etc ]

I would like two functions:

There must be an easy way?

Upvotes: 1

Views: 284

Answers (6)

user3760731
user3760731

Reputation:

hash = array.to_h => Converts your array to a hash
hash[key] = value => Get the value associated with the key
hash.invert[key] = value => This method inverts your hash and you can select values

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110685

I see no point in creating a hash to locate a single value. Why not the simple, direct approach?

values = [["a", 1], ["b", 3], ["c", 7]]

values.find { |l,n| l=='b' }.last  #=>  3
values.find { |l,n| n==3   }.first #=> "b"

Of course, neither of these deal with multiple values.

Upvotes: 0

ichigolas
ichigolas

Reputation: 7725

Yeah a hash is the answer, if you don't have duplicate keys of course. Otherwise you can use Array#assoc#rassoc which searches an array of arrays matching the first and last elements respectively:

ary =  [["A", 1], ["B", 2], ["C", 3], ["D", 4], ["E", 5], ["F", 6], ["G", 6]]
ary.assoc('A') => ["A", 1]
ary.rassoc('3') => ["C", 3]

Note: these methods return the first matching array, not all of them.

See more at http://www.ruby-doc.org/core-2.1.2/Array.html

Upvotes: 1

Peter Sorowka
Peter Sorowka

Reputation: 1036

The first is easy to achieve, by converting your array to a Hash with:

value_hash = Hash[values]

And access this with:

value_hash['b'] # => 3

For the other way around I would first like to know if you are sure that is is a unique request? So are both 'a','b','c',... and 1,3,7... etc. unique?

Upvotes: 2

CDub
CDub

Reputation: 13354

My first question is: Does this have to be an array? Hash is designed for this and has key / value lookup built-in.

You can create a Hash from an array by doing:

hash = Hash[values]

Then use hash["a"] # => 1

For the reverse, do: hash.key(1) # => "a"

Upvotes: 2

Matt
Matt

Reputation: 20786

Hash[values]["b"] # => 3
Hash[values.map(&:reverse)][3] # => "b"

Upvotes: 3

Related Questions