Search code examples
rubyobjectcomparison

ruby: check if two variables are the same instance


I have a class Issue in which each class has a key field. Because keys are meant to be unique, I overrode the comparison operator such that two Issue objects are compared based on key like so:

def ==(other_issue)
  other_issue.key == @key
end

However, I am dealing with a case in which two there may be two variables referring to the same instance of an Issue, and thus a comparison by key would not distinguish between them. Is there any way I could check if the two variables refer to the same place?


Solution

  • According to the source, the Object#equal? method should do what you're trying to do:

    // From object.c
    rb_obj_equal(VALUE obj1, VALUE obj2)
    {
        if (obj1 == obj2) return Qtrue;
        return Qfalse;
    }
    

    So the ruby code you would write is:

    obj1.equal?(obj2)