Backo
Backo

Reputation: 18901

How to get a value in a multidimensional array?

I am using Rails 3.1.0 and I would like to get a particular value from a multidimensional array. That is, I have the following

array = [ ['Text1', 's1'], ['Text2', 's2'], ['Text3', 's3'] ]

and, for example, I would like to search in the above array the string s3 so to get the corresponding value Text3. The same for s1 so to get the Text1 and for s2 so to get the Text2.

How can I make that?

Upvotes: 0

Views: 1158

Answers (1)

steenslag
steenslag

Reputation: 80105

For smallish arrays and infrequent lookups you can keep the array:

array = [ ['Text1', 's1'], ['Text2', 's2'], ['Text3', 's3'] ]
p array.rassoc('s3').first #=> 'Text3'

Upvotes: 3

Related Questions