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?
You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)
This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.
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]
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