Yuval Karmi
Yuval Karmi

Reputation: 26713

ruby soft delete_if method?

When I have an array in ruby, I can run a delete_if block on it. The problem is that it removes the elements from my array. I'd like the same functionality, except not make changes to the original array, but rather return a new array with the objects removed.

For example:

myarr = ["foo", 5, 7, "bar"]
newarr = myarr.delete_if { |e| e.is_a?(String) }

would return [5, 7] to newarr, but would also make modifications to the original array, myarr.

What I'm essentially looking for would be

myarr = ["foo", 5, 7, "bar"]
newarr = myarr.soft_delete_if { |e| e.is_a?(String) }

so that newarr will have the value [5, 7] but myarr would still have the same values.

Does something like this exist? Thanks a lot!

Upvotes: 2

Views: 930

Answers (2)

Mark Byers
Mark Byers

Reputation: 838276

Use reject.

> newarr = myarr.reject{ |e| e.is_a?(String) }
=> [5, 7]
> myarr
=> ["foo", 5, 7, "bar"]

There is also a related method called select which works in the same way as reject except it keeps the elements for which the predicate returns true instead of rejecting them.

Upvotes: 7

Chowlett
Chowlett

Reputation: 46667

You want Array#reject.

Upvotes: 3

Related Questions