12

I have a ruby array, and I want to sort all elements starting with index i till index j, in place. The rest of the array should not be modified. How can I implement this?

1
  • Well-worded question. @CodeGnome, admit it: you've been proved wrong. :-) Commented Apr 18, 2015 at 20:02

1 Answer 1

21

You can use the a[i, j] = a[i, j].sort! to sort from index i to index j. Example:

a = [8, 7, 5, 4, 3]
a[2..4] = a[2..4].sort!
a # => [8, 7, 3, 4, 5]
Sign up to request clarification or add additional context in comments.

4 Comments

I was going to comment it won't do what OP wants, but the change is good
Very nice, it seems you're on a roll today.
a[2..4] = a[2..4].sort! would be marginally more efficient, as it creates only one temporary array.
The example is correct, showing how to slice the array using a range, 2..4. The first line is not correct, as a[i, j] = a[i, j].sort does not sort from index i to index j, but sorts from index i and then a length of j.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.