0

(ruby 1.86)

I have an array made up of arrays like:

>> myArray 
=> [["apple", 1], ["bananna", 2], ["peach", 3], ["orange", 4]]

I know I can use the detect method to find the first instance of 'orange' in index[0] of the sub-arrays in MyArray:

myTest = (myArray.detect { |i| i[0] == 'orange' } || []).first
=> orange

If it's possible, how can I have the detect method return the value of the sup-array index position 1. Like, i[0] is being returned, but when i[0] == 'orange' I need i[1] returned.

I need to search for 'orange' and have the return value be 2.

Thank You!

1
  • Why do you want the return value to be 2? Given your description, I would have thought you want 4. Commented Jan 31, 2011 at 13:59

2 Answers 2

3

I suppose you want the return value to be 4. No need for #detect:

ar = [["apple", 1], ["bananna", 2], ["peach", 3], ["orange", 4]]
puts ar.assoc("orange").last

#=> 4
Sign up to request clarification or add additional context in comments.

3 Comments

Nice! +1. I always forget about assoc, as I've never found a need for it.
You know just reading the API I would have never figured the ".last" part out. There's no mention of how to point to a specific index of the sub-array that's found with the match. I guess if you understand arrays really well that kind of thing just comes to you? Again - thanks a bunch!
@Reno ar.assoc("orange")[1] is the same thing here.
2

I'd recommend using a hash. It better suits the usage you describe, and will be faster for large amounts of data.

fruit = {'apple'=>1, 'banana'=>2, 'peach'=>3, 'orange'=>4, 'kiwi'=>42}

puts fruit['orange'] #=> 4

But if you really want to retrieve the value from your subarray, change your first to last:

myTest = (myArray.detect { |i| i[0] == 'orange' } || []).last
#=> 4

Update: or even simpler, as @steenslag points out:

myTest = myArray.assoc("orange").last
#=> 4

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.