Thursday, January 27, 2011

Ruby "is" equivalent

Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location).

  • Use a.equal? b

    http://www.ruby-doc.org/core/classes/Object.html

    Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

  • You could also use __id__. This gives you the objects internal ID number, which is always unique. To check if to objects are the same, try

    a.__id__ = b.__id__

    This is how Ruby's standard library does it as far as I can tell (see group_by and others).

    From wvdschel

0 comments:

Post a Comment