开发者

delete from array returning self

If I want to delete some elements from an Array and return itself, are foo1 and foo2 below (foo2 when there is only one element to delete) the right way to do it?

class Array
    def foo1 *args; delete_if{|x| args.include?(x)} end
    def foo2 arg; dele开发者_StackOverflow社区te(arg); self end
end


class Array
 def foo3 (*args); self - args; end
end


array.reject{|element| element == value_of_element_to_be_deleted}


It's a little ugly, but the minus function does the trick concisely, subtracting one array from the other:

ary = [1, 2, 99, 3]
ary.-([99])

or

odds = [1, 3, 5, 7, 9, 99]
ary.-(odds)

The advantage here is that it is completely chainable (unlike .delete or ary - odds), so you can do things like:

ary.-(odds).average

Once your eye finds the minus sign, it's much easier to read, understand, and visually spot typos than the .delete_if construct.

It also plays well with Ruby's safe navigation operator, &., if you might get nil instead of an array. That's something you can't do elegantly with subtracting arrays.

maybe_array&.-(odds)&.average
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜