1

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?

4 Answers 4

1

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

2 Comments

So I guess this is the cleanest solution we have in Ruby? One thing that is not so perfect is that it has to take two iterations :)
@Innerpeacer You could do return a.clone - a.delete_if(&:good?) if you want.
1

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

1 Comment

Unfortunately, delete_if return the array itself, not the element being deleted.
1
 a = [e1, e2, e3]

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

 it will delete e1. and returns e2 and e3

Comments

1

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

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.