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?
-
Well-worded question. @CodeGnome, admit it: you've been proved wrong. :-)Cary Swoveland– Cary Swoveland2015-04-18 20:02:41 +00:00Commented Apr 18, 2015 at 20:02
Add a comment
|
1 Answer
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]
4 Comments
SwiftMango
I was going to comment it won't do what OP wants, but the change is good
Cary Swoveland
Very nice, it seems you're on a roll today.
Cary Swoveland
a[2..4] = a[2..4].sort! would be marginally more efficient, as it creates only one temporary array.Jochem Schulenklopper
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.