What's the Difference Between Array#reject! and Array#delete_if Methods in Ruby?

Both, Array#reject! and Array#delete_if, mutate (or modify) the original array and remove values from it that match a specified condition (provided in its block — i.e. the code between {...}). However, they differ in terms of their return values:

  • Array#reject! — returns the updated array if something was rejected, or returns nil otherwise;
  • Array#delete_if — returns the array (regardless of whether a value was deleted from the original array or not).

To demonstrate this, let's suppose you are trying to remove all odd numbers from an array of integers, that has no odd numbers:

numbers = [2, 4, 6, 8]
result = numbers.reject! { | item | item.odd? }

print result #=> nil

# original array is unchanged:
print numbers #=> [2, 4, 6, 8]
numbers = [2, 4, 6, 8]
result = numbers.delete_if { | item | item.odd? }

print result #=> [2, 4, 6, 8]

# original array is unchanged:
print numbers #=> [2, 4, 6, 8]

As you can see from the examples above, when Array#reject! does not modify the array, it returns nil, whereas, in the same instance, Array#delete_if returns the unchanged array.

When the provided condition in either of these methods match (i.e. their block evaluates to true), they have the same output (which is the modified array):

numbers = [1, 2, 3, 4]
result = numbers.reject! { | item | item.odd? }

print result #=> [2, 4]

# original array is changed:
print numbers #=> [2, 4]
numbers = [1, 2, 3, 4]
result = numbers.delete_if { | item | item.odd? }

print result #=> [2, 4]

# original array is changed:
print numbers #=> [2, 4]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.