Search code examples
rubylistsortingin-place

Ruby sort subarray in place


If I have an array in Ruby, foo, how can a sort foo[i..j] in-place?

I tried calling foo[i..j].sort! but it didn't sort the original array, just returned a sorted part of it.


Solution

  • If you want to sort part of an array you need to reinject the sorted parts. The in-place modifier won't help you here because foo[i..j] returns a copy. You're sorting the copy in place, which really doesn't mean anything to the original array.

    So instead, replace the original slice with a sorted version of same:

    test = %w[ z b f d c h k z ]
    
    test[2..6] = test[2..6].sort
    # => ["c", "d", "f", "h", "k"]
    
    test
    # => ["a", "b", "c", "d", "f", "h", "k", "q"]