Removing elements from an array non-destructively

993 Views Asked by At

Given an array arr and an object v, I want a copy of arr without the elements equal to v.

I found these two solutions:

newarr = arr.dup
newarr.delete(v)

and

newarr = arr.reject {|a| a == v}

Is there an easier way to do it?

I wonder whether Ruby already has something like:

newarr = arr.without(v)
1

There are 1 best solutions below

10
Aleksei Matiushkin On BEST ANSWER
[1, 2, 3, 4, 4, 5, 5] - [4]
#⇒ [1, 2, 3, 5, 5]

If this is too cumbersome for you too, use:

[1, 2, 3, 4, 4, 5, 5].reject(&4.method(:==))
#⇒ [1, 2, 3, 5, 5]