Last Updated: February 25, 2016
·
3.478K
· ciembor

Use .select! to remove elements from an array

You want to delete elements which doesn't fulfil a condition? Are you going to use a for loop or .each iterator?

array.each do |element|
  array.delete(element) if element.field < 1
end

It won't work! Some unexpected elements might be still in this array. It's because the array.length changes.

Use .select! instead:.

array.select! { |element| element.field >= 1 }

Or as @kv109 suggested, .reject!:

array.reject! { |element| element.field < 1 }

3 Responses
Add your response

I think Array#reject! is what you are looking for.

over 1 year ago ·

@kv109 Thanks, it's probably the most accurate method:).

over 1 year ago ·

I'd mention that there's select and reject alternatives on enumerable objects that do not mutate the original object (called the "receiver" in the context of message-passing). those come useful when you want to ensure the original object does not change but you need a filtered set of elements.

over 1 year ago ·