1

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; delete(arg); self end
end
2
  • 3
    It seems you could do with just passing an array to delete_if and use that without monkey-patching Array. Commented Feb 23, 2011 at 17:18
  • [1, 2, 3].delete_if([2, 4]) gives back an error. Commented Feb 24, 2011 at 3:12

3 Answers 3

2
class Array
 def foo3 (*args); self - args; end
end
Sign up to request clarification or add additional context in comments.

1 Comment

actually, what I want would be self -= args
0
array.reject{|element| element == value_of_element_to_be_deleted}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.