9

I looked really hard in http://www.ruby-doc.org/core-2.1.2/Array.html but I couldn't find a quick functionality to this behaviour:

arr = [1,2,3,4,5,6]

arr.without(3,6) #=> [1,2,4,5]

I know I can write my own function/monkey-patch ruby/add a class method/write it in a few lines.

Is there a way to do this in a ruby way?

0

4 Answers 4

21

you can use subtraction :

arr - [3,6]

EDIT

if you really wanted you could alias this method

class Array
  alias except - 
end

then you can use:

arr.except [3,6]
Sign up to request clarification or add additional context in comments.

4 Comments

I'm aware of array subtractions, is there a cleaner way to do this?
looks pretty clean to me !
yes, I use it a lot, if there is no other way I'll use that, thanks
Careful though, Array#- doesn't just subtract. It removes any instance of any item in the supplied parameter. So [1,2,3,3,3] - [2,3] => [1]. This may be something you don't expect.
16

This got added in Rails 5 :)

https://github.com/rails/rails/issues/19082

module Enumerable
  def without(*elements)
    reject { |element| element.in?(elements) }
  end
end

it's just aesthetics, but it makes sense for the brain

Comments

3

There is another way using reject. But it is not cleaner than -

arr.reject{|x| [3,6].include? x}

Comments

0

Just in case anyone else comes across this and is looking for a way to delete elements from an array based on a conditional: you can use delete_if.

For example, I have a list of customers and want to merge any customers that have duplicate emails. After doing a query to get a list of all emails with the total count number for each email, I can then delete all of them that only appear once:

emails = Customer.select('count(email) as num_emails, email').group('email')
emails.delete_if { |email| email.num_emails.to_i == 1 }

The end result is I have a list of all customer emails that appear multiple times in the database.

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.