From: Ross Bamford Date: 2005-12-22T06:07:49+09:00 Subject: Re: move to front of array On Wed, 21 Dec 2005 20:08:34 -0000, Payton Swick wrote: > Hi, > > I have an array of Strings, and I'd like to find one of the items by > Regexp, then move that item to the front of the array, eg: > > array = %w(a B c d Cool e f G) > array.unshift(array.slice!(array.index(array.find { |i| i =~ /cool/i > }))) if array.find { |i| i =~ /cool/i } > > Better/cleaner/shorter ways to do it? Not sure about better or cleaner, but here's a couple of ideas: Without error checking: (ary - [t = ary.detect { |$_| ~/cool/i }]).unshift(t) If you know there's only one of each element to start with, you could do: (ary.unshift(ary.detect { |$_| ~/cool/i })).uniq still without error checking, or: ary.unshift(ti).uniq if ti = ary.detect { |$_| ~/cool/i } To ensure you don't get a nil at the start, or ary.unshift(*ti).uniq if ti = ary.grep(/cool/i) to ensure you don't get flamed for using $_ ;) Of course, if you have dupes to start with this won't work. *** DISCLAIMER *** I am not advocating the default input space, I don't think you should use $_, it's only a few extra characters to do it the 'proper way', I just wanted to go for brevity here. *** :) -- Ross Bamford - rosco@roscopeco.remove.co.uk