Innerpeacer
Innerpeacer

Reputation: 1321

Delete an element from an Array based on a condition block and return that element

Is there a quick Ruby or Rails method to delete an element from an Array based on a condition provided in a block and then return that element?

Let's say, given:

e1.good? # false
e2.good? # true
e3.good? # true
a = [e1, e2, e3]

Is there a method delete_and_return_if doing this:

a.delete_and_return_if { |e| e.good? }      # delete e2 from a and returns e2
[e1].delete_and_return_if { |e| e.good? }   # returns nil

Or at least is there a clean way to do this?

Upvotes: 1

Views: 1206

Answers (4)

user904990
user904990

Reputation:

This will update array and return deleted entry:

a = [1, 2, 3]

p a
# => [1, 2, 3]

deleted = a.delete a.detect {|e| e == 2 }
p deleted
# => 2

p a
# => [1, 3]

so you can do like this:

a.delete a.detect(&:good?)

UPDATE: thanks to @oldergod for recalling me about detect

Upvotes: 1

oldergod
oldergod

Reputation: 15010

If you do not have duplicates or that you want to delete all same elements, you can do

a.delete(a.detect(&:good?))
  • a.detect(&:good?) will return the first good? object or nil if there is none.
  • a.delete(elem) will delete and return your element.

Or if you have duplicates and only want to delete the first one:

a.delete(a.index(a.detect(&:good?)))

Upvotes: 1

vijikumar
vijikumar

Reputation: 1815

 a = [e1, e2, e3]

 a.delete_if{|e|!e.good?}

 it will delete e1. and returns e2 and e3

Upvotes: 1

There is delete_if, this is a Ruby function. http://www.ruby-doc.org/core-1.9.3/Array.html

Upvotes: 1

Related Questions