This question already has an answer here:
- Uniq by object attribute in Ruby 13 answers
What if instead of removing duplicate elements from an array, I want to remove elements that have a specific property in common?
Specifically, I want to remove all strings from an array with duplicate "essences", where essence is defined like this:
class String
def essence
downcase.gsub('&', 'and').gsub(/[^a-z0-9]/, '')
end
end
I want something like this:
['a', 'A', 'b'].uniq_by(&:essence)
# => ['a', 'b'] (or ['A', 'b']; I don't really care)
What's the best way to accomplish this?
Activesupport has a Array#uniq_by, and this is the code:
Facets also has a Enumerable#uniq_by:
Quick and dirty way:
And some monkey patching:
Since 1.9.2,
Array#uniq
(anduniq!
) takes a block, so no more need foruniq_by
.