Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

originals indexes of sorted elements in Ruby

arr = [1,3,2,4]

arr.sort #=> [1,2,3,4]

I would like an array [0, 2, 1, 3] (original indexes in arr.sort order)

Is there a simple way to do that with Ruby 1.9.3?

thank you

like image 383
szymanowski Avatar asked Jan 21 '13 19:01

szymanowski


People also ask

How do you find the index of an element in Ruby?

Array#find_index() : find_index() is a Array class method which returns the index of the first array. If a block is given instead of an argument, returns the index of the first object for which the block returns true.

What is <=> in Ruby sort?

The Ruby sorting operator ( <=> )Also called the spaceship operator, takes two parameters and returns one of three values. 0 if the two parameters are equal. -1 if the first parameter is less than the second parameter. 1 if the first parameter is greater than the second parameter.

How do you use the index method in Ruby?

index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found.


1 Answers

xs = [1, 3, 2, 4]
original_indexes = xs.map.with_index.sort.map(&:last)
#=> [0, 2, 1, 3]
like image 111
tokland Avatar answered Nov 04 '22 10:11

tokland