Forum: Ruby Re: move to front of array

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Daniel S. (Guest)
on 2005-12-22 03:12
(Received via mailing list)
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
#####################################################################################
This topic is locked and can not be replied to.