Mungomash

Chad Dalton - hacker

Dedupe an Array in Ruby

| Comments

Deduping an array in Ruby using the uniq method is simple.

1
["a", "a", "b", "b", "c"].uniq   #=> ["a", "b", "c"]

Deduping an array of objects based on a specific attibute can be more complicated.

Rails includes a uniq_by method.

1
[1, 2, 3, 4].uniq_by { |i| i.odd? } # => [1, 2]

If you are working without Rails, the Hash works nicely since it allows only one instance of each key.

1
2
a = [1, 2, 3, 4]
Hash[*a.reverse.map{|i|[i.odd?,i]}.flatten].values # => [1, 2]

Comments