Inspecting from source of Diff::LCS
, the elements in sequences are used as hash key.
The Element
class you wrote mixed the Comparable module, it got the ==
method there. However, it doesn't have eql?
and hash
method override, which is used by the Hash
to determine the key comparison.
With you Element
class, we have
irb(main):013:0> a = Element.new("a")
=> #<Element:0x002ae4ce402da0 @name="a">
irb(main):014:0> b = Element.new("a")
=> #<Element:0x002ae4ce409ec0 @name="a">
irb(main):015:0> a == b
=> true
irb(main):016:0> a.eql? b
=> false
irb(main):017:0> a.hash == b.hash
=> false
irb(main):018:0> h = {}
=> {}
irb(main):019:0> h[a] = 1
=> 1
irb(main):020:0> h[b]
=> nil
This affects the LCS calculation.
The fix is to add the eql?
and hash
method for the Element
class, I think.
class Element
include Comparable
attr_reader :name
def initialize(name)
@name = name
end
def <=>(other)
@name <=> other.name
end
def eql? other
other.class == Element and self.name == other.name
end
def hash
@name.hash ^ Element.hash
end
end