Project

General

Profile

Actions

Feature #10523

closed

Suggestion for new Array.delete_to method

Added by garysweaver (Gary Weaver) almost 10 years ago. Updated almost 10 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:66348]

Description

Array's delete and delete_at return the deleted item from an array, so it would seem as though Array should allow some sort of delete method that could take a block and would return the deleted items that matched as an array.

Currently the hack for this posted at http://stackoverflow.com/a/5480449/178651 is to use delete_if, but have to store the matched value to delete in a separate array, e.g.:

reject = []
=> []
content = [1,2,3,4,5,6,7,8,9]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
content.delete_if {|v| reject << v if v > 5}
=> [1, 2, 3, 4, 5]
reject
=> [6, 7, 8, 9]

However, what if there were a more elegant way of doing this, like:

content = [1,2,3,4,5,6,7,8,9]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
content.delete_to {|v| if v > 5}
=> [6, 7, 8, 9]

And you could also store the delete values in an existing array like:

content = [1,2,3,4,5,6,7,8,9]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
content.delete_to([:a, :b]) {|v| if v > 5}
=> [:a, :b, 6, 7, 8, 9]

Or to remove and transfer the entire contents of one array to another array:

a = [1,2,3,4,5,6,7,8,9]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = []
=> []
content.delete_to(b)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
a
=> []
b
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

In which case, delete_to could be aliased as move_to.

The primary use case though is the first-it would be helpful to matching items from an array, remove them from that array, and return the removed items.

Updated by garysweaver (Gary Weaver) almost 10 years ago

Oops, in that last code example, I meant: a.delete_to(b).

Updated by matz (Yukihiro Matsumoto) almost 10 years ago

  • Status changed from Open to Rejected

I prefer Array#partition for its immutability.

Matz.

Actions

Also available in: Atom PDF

Like0
Like0Like0