pusewicz · GitHub

Defining == method on an object so that it's used for comparison when using Array#delete causes an exception. For some reason, the other becomes an Object, rather than Cell.

Sample code

class Cell
  attr_accessor :id
  def initialize
    @id = rand(1_000_000)
  end
  def ==(other)
    @id == other.id
  end
  def id
    @id
  end
end
cells = Array.new(1_000) { Cell.new }
1_000.times do |i|
  cells.delete(cells.sample)
end
puts "There are #{cells.size} cells left."

Expected

$ mruby test.rb
There are 0 cells left.

Actual

$ mruby test.rb
trace (most recent call last):
        [2] mruby.rb:18
        [1] mruby.rb:19
test.rb:9:in ==: undefined method 'id' (NoMethodError)

Read the original on github.com ↗