2

I got 2 arrays:

a = [1,2,3,4,5]
b = [4,5,6,7,8]

I want to delete every b element in a, in order for a to have [1,2,3]

Of course, my real arrays are different.

I want a beautiful answer with a simple method, since I can resolve this issue by using this loop, but I find it ugly.

b.each do |e|
  a.delete(e) if a.include?(e)
end
return a

It seems that reject may be the way to go, but couldn't find the good way. Thanks you

1
  • 1
    do a-b to get what you wanted. Commented Mar 31, 2014 at 13:59

1 Answer 1

6

Just do as below using Array Difference :-

a = [1,2,3,4,5]
b = [4,5,6,7,8]
a = a - b
a # => [1,2,3]

But I would suggest, don't modify the source array. Rather do

new_ary = a - b
Sign up to request clarification or add additional context in comments.

2 Comments

Beautiful ! Thanks, Accepted; could you tell me how to use the reject method by the way please (is it possible to use it here) ?
@sidney You can use - a.reject { |e| b.include?(e) } .. But Array#- is perfect for this.

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.