# Array.uniq on specific attributes

**URL:** <https://rubytalk.org/t/array-uniq-on-specific-attributes/64921>\
**Category:** ruby-talk\
**Created:** [20 February 2012 18:11 UTC](https://rubytalk.org/t/array-uniq-on-specific-attributes/64921 "2012-02-20T18:11:30Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kenichi\_Kamiya](https://avatars.discourse-cdn.com/v4/letter/k/ecccb3/32.png) [@Kenichi\_Kamiya](https://rubytalk.org/u/Kenichi_Kamiya)\
**Post date:** [20 February 2012 18:11 UTC](https://rubytalk.org/t/array-uniq-on-specific-attributes/64921/1 "2012-02-20T18:11:30Z")

</div>

# an approach

class Array  
private

def \_uniq\_by(&block)  
new, memo = [], {}

```
map\(&amp;block\)\.each\_with\_index do |mapped, idx|
  unless memo\[mapped\]
    memo\[mapped\] = true
    new &lt;&lt; self\[idx\]
  end
end

new

```

end

alias\_method :\_uniq, :uniq  
alias\_method :\_uniq!, :uniq!

public

def uniq(&block)  
block\_given? ? \_uniq\_by(&block) : \_uniq  
end

def uniq!(&block)  
if block\_given?  
new = \_uniq\_by(&block)

```
  if self == new
    nil
  else
    replace\(new\)
  end
else
  \_uniq\!
end

```

end  
end

# 1.9.2 original

> **[Ideone.com](https://ideone.com/Uygbz)**
>
> Ideone is something more than a pastebin; it's an online compiler and debugging tool which allows to compile and run code online in more than 40 programming languages.

# same return from 1.8.6, 1.8.7, 1.9.2, 1.9.3

> **[Ideone.com](https://ideone.com/ySoIE)**
>
> Ideone is something more than a pastebin; it's an online compiler and debugging tool which allows to compile and run code online in more than 40 programming languages.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).
