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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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.
1 2 3 4 | 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 nil
s from the array, you may not be able to check that it was removed because nil is returned as the value that was removed.
1 2 3 4 5 6 | 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.
1 2 3 4 5 6 7 8 | 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.
1 2 3 4 5 6 7 8 9 10 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 | 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