Search code examples
rubyuniquemonkeypatching

Extending uniq method


This is Ruby 1.8 Question:

We all know how to use Array#uniq :

[1,2,3,1].uniq #=> [1,2,3]

However I'm wondering if we can monkey patch it in a way to work with complex objects. The current behavior is like this:

[{"three"=>"3"}, {"three"=>"4"}, {"three"=>"3"}].uniq 
#=> [{"three"=>"3"}, {"three"=>"4"}, {"three"=>"3"}]

The requested one is:

[{"three"=>"3"}, {"three"=>"4"}, {"three"=>"3"}].uniq 
#=> [{"three"=>"3"}, {"three"=>"4"}]

Solution

  • It already works for me in 1.8.7.

    1:~$ ruby -v
    ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]
    1:~$ irb -v
    irb 0.9.5(05/04/13)
    1:~$ irb
    >> [{"three"=>"3"}, {"three"=>"4"}, {"three"=>"3"}].uniq 
    => [{"three"=>"3"}, {"three"=>"4"}]