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
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.
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.
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.
xs = [1, 3, 2, 4]
original_indexes = xs.map.with_index.sort.map(&:last)
#=> [0, 2, 1, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With