开发者

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 val开发者_如何学运维ue [5, 7] but myarr would still have the same values.

Does something like this exist? Thanks a lot!


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.


You want Array#reject.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜