I tested MRI Ruby 2.2.1p85 (on both Mac and CentOS), the tokland solution returns the wrong result:
xs = [8,3,2,7,5] xs.map.with_index.sort.map(&:last)
Evgeny Anfilofeev's solution works, but does not support an unhistorical array:
arr = [8,3,2,7,5] arr_s = arr.sort arr.map{|e| arr_s.index(e)}
I approach this:
arr = [8,3,5,2,8,8,7,5] index_order = [] arr.uniq.sort.each do |a| index_order += arr.each_index.select{|i| arr[i] == a } end r = [] index_order.each_with_index do |a, i| r[a] = i end r
source share