From: "Simon Kröger" Date: 2005-12-22T19:46:44+09:00 Subject: Re: move to front of array No inject solution? here it is: array = %w(a B c d Cool e f G) p array.inject([]){|s, o| o =~ /cool/i ? [o, *s] : s << o} => ["Cool", "a", "B", "c", "d", "e", "f", "G"] cheers Simon Devin Mullins wrote: > 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? > > > I'm going to do something controversial and suggestion a completely > imperative method: > > array.each_with_index {|o,i| array.unshift(array.delete_at(i)) if o =~ > /cool/i} > > Oddly, this works with multiple instances of Cool. I take it that > #each_with_index doesn't miss a beat wrt the modifications. > > Oh, and if you'll be doing it more than once in your code, then put the > method where it belongs: > class Array > def bubble_if!(regex=nil) > if block_given? then each_with_index {|o,i| unshift(delete_at(i)) if > yield o} > else super() {|o| =~ regex} > end > end > end > array.bubble_if!(/cool/i) > > Devin > YMMV. > > >