Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to extend Core class comparison methods
    primarykey
    data
    text
    <p>I'd like my class to be <a href="http://blog.rubybestpractices.com/posts/rklemme/018-Complete_Class.html" rel="nofollow">complete</a> for several anticipated scenarios, including object comparison. My class is <code>Hash</code>-like in that it has a method <code>to_hash</code>, on which many of my class-completing methods are based. For example:</p> <pre><code>class Hashlike def == other if other.respond_to?(:to_hash) to_hash == other.to_hash end end end </code></pre> <p>It seems overkill to override <code>Hash#==</code> just to inject similarity into the message's superchain:</p> <pre><code>class Hash def == other # Flip the comparison other.is_a?(Hashlike) ? other == self : super end end </code></pre> <p>This will end up in stacktraces everywhere for entirely irrelevant issues. This feels invasive.</p> <p>Is there a preferred or less invasive way to make <code>Hash</code> aware of my <code>Hashlike</code>'s eligibility for comparison? And in general, is there a convention for extending core objects (<code>Hash</code>, <code>Array</code>) to receive core interface messages (<code>==</code>, <code>nil?</code>, <code>&lt;==&gt;</code>) and be aware of custom classes without leaving fingerprints all over their superchains?</p> <p><strong>Update:</strong></p> <p>The only optimization that occurs to me is to make the override call super <em>first</em> in the hopes of not choking a potentially heavily-used method with early conditional branching:</p> <pre><code>class Hash def == other # Lazily delay the comparison super or (other == self if other.is_a?(Hashlike)) end end </code></pre> <p>Some careful benchmarking (to the order of 1 billion comparisons) suggests that using either approach performs just as well as ruby's default of reversing the comparison if <code>to_hash</code> is defined on the received object, as mentioned in the answer below.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload