Project

General

Profile

Actions

Feature #18395

open

Introduce Array#subtract! for performance

Added by schneems (Richard Schneeman) over 2 years ago. Updated over 2 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:<unknown>]

Description

PR: https://github.com/ruby/ruby/pull/5110#issuecomment-984345309

It is common to use -= to modify an array to remove elements. Also, there is Array#difference which accepts multiple arguments. Both of these methods allocate an intermediate array when the original array could be re-used.

I am proposing we add an API onto Array that allows the programmer to perform a subtraction/difference operation and mutate the original array.

I am proposing Array#subtract!. Reasons why I did not choose Array#difference! are discussed in the comments of the PR. I'm also happy to discuss alternative names.

ary = [0, 1, 1, 2, 1, 1, 3, 1, 1]
ary.subtract!([1]) #=> [0, 2, 3]
ary                #=> [0, 2, 3]

ary = [0, 1, 2, 3]
ary.subtract!([3, 0], [1, 3]) #=> [2]
ary                           #=> [2]
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0