james
james

Reputation: 4049

Find first value of inner array based on second value

I have

@array = [
  ["Single - Tuesday - $13/meal", 1],
  ["Trifecta - Mon, Wed, Fri - $12/meal", 3],
  ["Quinary - Every weekday - $11/meal", 5]
] 

If I have the second value of the inner array 1, 3, or 5, what's the easiest way to pull the first value? I.e.,

some_method_or_whatever(1) # => "Single - Tuesday - $13/meal"
some_method_or_whatever(3) # => "Trifecta - Mon, Wed, Fri - $12/meal"
some_method_or_whatever(5) # => "Quinary - Every weekday - $11/meal"

Upvotes: 0

Views: 53

Answers (3)

sawa
sawa

Reputation: 168081

@array.rassoc(1).first
# => "Single - Tuesday - $13/meal"

Upvotes: 4

osman
osman

Reputation: 2469

Are the second values going to be unique? Why not a hash?

hash =
   {1 => "Single - Tuesday - $13/meal", 
   3 => "Trifecta - Mon, Wed, Fri - $12/meal", 
   5 => "Quinary - Every weekday - $11/meal"}

hash[1], hash[3] etc

But if it has to be what you're asking do the numbers follow the same pattern and position? i.e. 1,3,5,7,9 etc? If so @array.flatten[value] will work.

Otherwise @array[@array.flatten.find_index(5)-1], but obv only works if value is unique.

Upvotes: 0

AbM
AbM

Reputation: 7779

You can use the find method:

@array.find{|sub_array| sub_array[1] == <your value here>}.try(:first)

Upvotes: 1

Related Questions