From: Peter Thoman Date: 2006-02-07T18:28:30+09:00 Subject: Re: Feeling sharp? Sort an array subset in place. Michael Judge wrote: >Here's the situation: I have an array and I'd like to sort certain >elements in place -- without touching the others. > >Unsorted array contents: > 3 <-- sort me! > x > 1 <-- sort me! > y > 2 <-- sort me! > >Sorted array contents > 1 > x > 2 > y > 3 > >See how 1, 2, and 3 played musical chairs? That's exactly what we >want. It seems like there should be an easy one, two or three-line way >to do this given an array and a test condition (for identifying >elements which need sorting.) > >How would you do it? > I'm definitely *not* feeling sharp (10 AM here and I haven't slept yet) but here's my try: arr = [3,:x,1,:y,2] # => [3, :x, 1, :y, 2] sorted = arr.select { |v| v.class == Fixnum }.sort # => [1, 2, 3] arr.map { |v| v.class == Fixnum ? sorted.shift : v } # => [1, :x, 2, :y, 3] Of course, substitute conditions as appropriate. - Peter