Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting part of an array in Ruby

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?

like image 324
kpriya Avatar asked Apr 18 '15 19:04

kpriya


People also ask

How do you sort an array of elements in Ruby?

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)

How can you test if an item is included in an array Ruby?

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.


1 Answers

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]
like image 180
JuniorCompressor Avatar answered Oct 01 '22 01:10

JuniorCompressor