Ruby Tuesday – Array#delete

Today’s Ruby Tuesday covers Array#delete.

Array#delete removes all items in the array that are equal to the object passed as an argument to the method.

list = [1, 2, 1, 3, 1, 5]
# => [1, 2, 1, 3, 1, 5]
list.delete(1)
# => 1
list
# => [2, 3, 5]
list.delete(3)
# => 3
list
# => [2, 5]

mississippi = "Mississippi".chars
# => ["M", "i", "s", "s", "i", "s", "s", "i", "p", "p", "i"]
mississippi.delete("s")
# => "s"
mississippi
# => ["M", "i", "i", "i", "p", "p", "i"]

Array#delete by default returns nil if the item was not found in the list.

no_fours = [1, 2, 3, 5, 6, 7]
# => [1, 2, 3, 5, 6, 7]
no_fours.delete(4)
# => nil

But if you decide to use Array#delete to remove nils from the array, you may not be able to check that it was removed because nil is returned as the value that was removed.

contains_nil = [1, "a", nil, :foo]
# => [1, "a", nil, :foo]
contains_nil.delete(nil)
# => nil
contains_nil
# => [1, "a", :foo]

If you come across that scenario, Array#delete allows you to specify a block that gets called if the item was not found in the array.

contains_nil2 = [1, "a", nil, :foo]
# => [1, "a", nil, :foo]
contains_nil2.delete(nil) {:bar}
# => nil
contains_nil2
# => [1, "a", :foo]
contains_nil2.delete(nil) {:bar}
# => :bar

As mentioned above, Array#delete removes all items that are equal to the argument passed in. The catch is Ruby has three different equality comparisons: ==, eql?, and equal?. So let’s try a couple of different scenarios to see which equality operator Ruby uses when doing an equality check.

mississippi = "Mississippi".chars
# => ["M", "i", "s", "s", "i", "s", "s", "i", "p", "p", "i"]
mississippi.delete("s")
# => "s"
"s" == "s"
# => true
"s".eql? "s"
# => true
"s".equal? "s"
# => false

So it looks like it is not equal?, but we still have == and eql? left that it could be, so let’s try another scenario.

integers = [1, 2, 3, 4]
# => [1, 2, 3, 4]
integers.delete(1.0)
# => 1
integers
# => [2, 3, 4]
1 == 1.0
# => true
1.eql? 1.0
# => false
1.equal? 1.0
# => false

As we can see here, 1 was removed when 1.0 was passed as an argument, so we see that Array#delete uses the == equality check to determine if the items are equal.

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *