Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I get the unique elements from an array of hashes in Ruby?
    primarykey
    data
    text
    <p>I have an array of hashes, and I want the unique values out of it. Calling <code>Array.uniq</code> doesn't give me what I expect.</p> <pre><code>a = [{:a =&gt; 1},{:a =&gt; 2}, {:a =&gt; 1}] a.uniq # =&gt; [{:a =&gt; 1}, {:a =&gt; 2}, {:a =&gt; 1}] </code></pre> <p>Where I expected:</p> <pre><code>[{:a =&gt; 1}, {:a =&gt; 2}] </code></pre> <p>In searching around on the net, I didn't come up with a solution that I was happy with. Folks recommended redefining <code>Hash.eql?</code> and <code>Hash.hash</code>, since that is what <code>Array.uniq</code> is querying.</p> <p>Edit: Where I ran into this in the real world, the hashes were slightly more complex. They were the result of parsed JSON that had multiple fields, some of which the values were hashes as well. I had an array of those results that I wanted to filter out the unique values.</p> <p>I don't like the redefine <code>Hash.eql?</code> and <code>Hash.hash</code> solution, because I would either have to redefine <code>Hash</code> globally, or redefine it for each entry in my array. Changing the definition of <code>Hash</code> for each entry would be cumbersome, especially since there may be nested hashes inside of each entry.</p> <p>Changing <code>Hash</code> globally has some potential, especially if it were done temporarily. I'd want to build another class or helper function that wrapped saving off the old definitions, and restoring them, but I think this adds more complexity than is really needed.</p> <p>Using <code>inject</code> seems like a good alternative to redefining <code>Hash</code>.</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.
 

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