From: Robert Klemme Date: 2006-02-07T18:23:20+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'd change the app design to not have these arrays. Seriously. It seems as if you were storing things together that do not belong together. Why do you need that? Kind regards robert irb(main):001:0> a=[3,"y",1,"x",2] => [3, "y", 1, "x", 2] irb(main):002:0> s=a.select {|x| Integer === x}.sort => [1, 2, 3] irb(main):003:0> i=0 => 0 irb(main):004:0> a.map! {|e| Integer === e ? (r=s[i]; i+=1; r) : e} => [1, "y", 2, "x", 3]