[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: move to front of array

Daniel Sheppard

12/22/2005 1:10:00 AM

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(


> -----Original Message-----
> From: Dan Diebolt [mailto:dandiebolt@yahoo.com]
> Sent: Thursday, 22 December 2005 8:39 AM
>
> >That certainly would work (assuming that only one element matches the
> condition),
>
> seems to work on multiple matches:
>
> array = %w(a B c d Cool e f G Cool Cooler)
> => ["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
#####################################################################################