# Any Array method to delete elements and return them?

**URL:** <https://www.ruby-forum.com/t/any-array-method-to-delete-elements-and-return-them/180078>\
**Category:** Ruby\
**Created:** [December 10, 2009, 11:52pm UTC](https://www.ruby-forum.com/t/any-array-method-to-delete-elements-and-return-them/180078 "2009-12-10T23:52:43Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ISSSSaki\_Baz\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/51bf81/32.png) [@ISSSSaki\_Baz\_C](https://www.ruby-forum.com/u/ISSSSaki_Baz_C)\
**Post date:** [December 10, 2009, 11:52pm UTC](https://www.ruby-forum.com/t/any-array-method-to-delete-elements-and-return-them/180078/1 "2009-12-10T23:52:43Z")

</div>

Hi, I’ve an array like this:

a = [1,2,3,“aaa”,“bbb”,4,“ccc”]

I want to remove from the array all the Strings, but also want these  
Strings  
in a new Array.

Array#delete\_if of Array#reject! is not valid because they delete  
elements but  
don’t return them, but the modified array:

a.reject! {|e| e.is\_a?(String)}  
=\> [1, 2, 3, 4]

a.delete\_if {|e| e.is\_a?(String)}  
=\> [1, 2, 3, 4]

I want a method that deletes elements from the array and return the  
deleted  
elements, somethis as:

a.delete\_and\_extract\_if {|e| e.is\_a?(String)}  
=\> [“aaa”, “bbb”, “ccc”]

Does such method exist?

PS: Of course I can do it by using Array#collet and Array#reject! in two  
different commands, but would like it to be more efficient.

Thanks.

---

<div class="post-metadata">

**Author:** ![ISSSSaki\_Baz\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/51bf81/32.png) [@ISSSSaki\_Baz\_C](https://www.ruby-forum.com/u/ISSSSaki_Baz_C)\
**Post date:** [December 11, 2009, 12:12am UTC](https://www.ruby-forum.com/t/any-array-method-to-delete-elements-and-return-them/180078/2 "2009-12-11T00:12:49Z")

</div>

IÃ±aki Baz C. wrote:

> Hi, I’ve an array like this:
> 
> a = [1,2,3,“aaa”,“bbb”,4,“ccc”]
> 
> I want to remove from the array all the Strings, but also want these  
> Strings  
> in a new Array.

strings, a = a.partition{|e| e.is\_a?(String)}

hth,

Siep

---

<div class="post-metadata">

**Author:** ![ISSSSaki\_Baz\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/51bf81/32.png) [@ISSSSaki\_Baz\_C](https://www.ruby-forum.com/u/ISSSSaki_Baz_C)\
**Post date:** [December 11, 2009, 12:19am UTC](https://www.ruby-forum.com/t/any-array-method-to-delete-elements-and-return-them/180078/3 "2009-12-11T00:19:37Z")

</div>

El Viernes, 11 de Diciembre de 2009, Siep K. escribiÃ³:

> IÃ±aki Baz C. wrote:
> 
> > Hi, I’ve an array like this:
> > 
> > a = [1,2,3,“aaa”,“bbb”,4,“ccc”]
> > 
> > I want to remove from the array all the Strings, but also want these  
> > Strings  
> > in a new Array.
> 
> strings, a = a.partition{|e| e.is\_a?(String)}

Great!
