0

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) 
6
  • 1
    Note that Ruby 1.9 is no longer supported by the core Ruby team. If it's at all possible, migrate to something in the 2.x series. 2.4.1 is current. Commented Jul 18, 2017 at 15:52
  • 1
    Simply put, you are asking for a non-destructive version of delete. Commented Jul 18, 2017 at 16:11
  • @engineersmnky oops, I didn't read the documentation of Array#delete carefully and I ignored its return value. You are right. Commented Jul 18, 2017 at 17:24
  • grep_v may be useful but uses === instead of == so it's not the same thing. Commented Jul 19, 2017 at 0:51
  • @tadman: I would love to. It's not my decision... Commented Jul 19, 2017 at 7:04

1 Answer 1

9
[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] 
Sign up to request clarification or add additional context in comments.

10 Comments

@MarkThomas Let me guess: Array#-? :)
Hint: I'm considering putting it on a list of things to reject in a code review :)
@MarkThomas yeah, the censorship, we know how it happens when the democracy to use shortcuts suffers under the yoke of the senior dictators!
@MarkThomas Liberty or Death .reject(&:==.to_proc.curry(2).call(4)) :)
That is why I have monkeypatched Object to alias method as m in all my projects. Once for all saving 5 chars!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.