On Wed, 21 Dec 2005 20:08:34 -0000, Payton S. [email protected]
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.