ordinary
ordinary

Reputation: 6133

Ruby array delete vs delete(bang)

I thought Array#delete deleted all copies of an object in an array, but some weird (and inexplicable to me) things are happening in this program I am writing. Delete only seems to work when I include a bang at the end of the delete function, even though that doesn't seem to be defined.

Here is the function in question:

  def propagate
    @puzzle.each do |sqr, values|
      if values.length == 1
        @neighbors[sqr].each do |neighbor|
          @puzzle[neighbor].delete!(values)
        end 
      end 
    end 
  end 

@puzzle is a hash with strings as keys and values, formatted like so: @puzzle["A1"] = "123456789"

@neighbors is a hash with strings as keys and arrays of strings as values:

@neighbors["A1"] = ["A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "B1", "C1", "D1", "E1", "F1", "G1", "H1", "I1", "B2", "B3", "C2", "C3"]

when I run the code like this: @puzzle[neighbor].delete(values)

The values in puzzle are unaffected by the delete. But when I include the ! it works.

Why is this?

Upvotes: 0

Views: 1360

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

It's a common idiom. Bang methods modify object in-place, "normal" methods return a modified copy.

The delete! method call you're performing is against a string, not an array. And String does indeed have method delete!: http://www.ruby-doc.org/core-1.9.3/String.html#method-i-delete-21

Upvotes: 5

Related Questions