Nick Ginanto
Nick Ginanto

Reputation: 32120

returning array without specific elements in ruby

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?

Upvotes: 9

Views: 10436

Answers (4)

mmcc8394
mmcc8394

Reputation: 31

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.

Upvotes: 0

Nick Ginanto
Nick Ginanto

Reputation: 32120

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

Upvotes: 16

nishu
nishu

Reputation: 1493

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

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

Upvotes: 3

Ian Kenney
Ian Kenney

Reputation: 6426

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]

Upvotes: 21

Related Questions