From: Payton Swick Date: 2005-12-22T23:56:09+09:00 Subject: Re: move to front of array Just for the sake of completeness, here is Devin's suggestion, with syntax errors corrected: class Array def bubble_if!(regex=nil) if block_given? then each_with_index {|o,i| unshift(delete_at(i)) if yield o} else bubble_if! {|o| o =~ regex} end end end Thanks for the suggestions, everyone! -Payton 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. >