Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 587
scottysseus Avatar asked Jul 22 '15 18:07

scottysseus


1 Answers

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)
like image 56
fresskoma Avatar answered Nov 04 '22 01:11

fresskoma