From: Ross Bamford Date: 2006-02-07T23:12:11+09:00 Subject: Re: Feeling sharp? Sort an array subset in place. On Tue, 2006-02-07 at 17:28 +0900, 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. I agree with Robert that you should probably think about why your data is kept this way. But here's one I've used: class Array def select_sort!(sort_proc = nil) t = [] map! { |x| if yield x then t << x; nil else x end } t.sort!(&sort_proc) map! { |x| x or t.shift } end end Which works like: a = [2,'a',3,'b','c',1] >> # => [2, "a", 3, "b", "c", 1] a.select_sort! { |x| x.is_a? Fixnum } >> p a # => [1, "a", 2, "b", "c", 3] a.select_sort!(lambda { |x,y| y <=> x }) { |x| x.is_a? Fixnum } >> p a # => [3, "a", 2, "b", "c", 1] But it breaks down if your array contains nil elements beforehand, and has that nasty two-block look about it. -- Ross Bamford - rosco@roscopeco.REMOVE.co.uk