How can I find the index of the second greatest element in my array?
问题 I'm using Ruby 2.4 and I have an array of numbers: [23423, 349843, 13123, 29239, 20201, ...] How can I find the array index corresponding to the second greatest value in the array? You can assume that there are at least two elements in the array. 回答1: Try this one. a is your array a.index(a.max(2).last) 回答2: a = [1,3,1,2] When 1 and 1 are regarded as the two smallest values of a def second_largest_not_uniq(a) a.each_index.min_by(2) { |i| a[i] }[1] end second_largest_not_uniq [1,3,1,2] #=> 2