开发者

Array detect method - return the value of a specific sub-array index?

(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!


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜