# Re: move to front of array

**URL:** <https://www.ruby-forum.com/t/re-move-to-front-of-array/74310>\
**Category:** Ruby\
**Created:** [December 22, 2005, 2:12am UTC](https://www.ruby-forum.com/t/re-move-to-front-of-array/74310 "2005-12-22T02:12:34Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dasch](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b2d939/32.png) [@dasch](https://www.ruby-forum.com/u/dasch)\
**Post date:** [December 22, 2005, 2:12am UTC](https://www.ruby-forum.com/t/re-move-to-front-of-array/74310/1 "2005-12-22T02:12:34Z")

</div>

While flatten might be acceptable for this usecase, be aware that if you  
have nested arrays, that nesting will be lost.

a,b = array.partition {|x| x =~ /cool/i}  
array = a+b

is safer, or alternatively:

class Array  
def flatten\_once  
self.inject([]) {|a,x| a.concat(x)}  
end  
end

array = array.partition {|x| x=~ /cool/i}.flatten\_once

Unless you only want one of the matching elements to move forward:

looking = true  
array = array.partition {|x| looking && !(looking = !(x=~ /cool/i))  
}.flatten\_once

or

array = array.index(

> =\> [“a”, “B”, “c”, “d”, “Cool”, “e”, “f”, “G”, “Cool”, “Cooler”]  
> array = array.partition{ |el| el =~ /cool/i }.flatten!  
> =\> [“Cool”, “Cool”, “Cooler”, “a”, “B”, “c”, “d”, “e”, “f”, “G”]
> 
> I was uncertain about needing parenthesis before applying  
> flatten but it makes perfect sense:
> 
> array = (array.partition{ |el| el =~ /cool/i }).flatten!  
> #####################################################################################  
> This email has been scanned by MailMarshal, an email content filter.  
> #####################################################################################  
> #####################################################################################  
> This e-mail message has been scanned for Viruses and Content and cleared  
> by NetIQ MailMarshal  
> #####################################################################################
