metronome
metronome

Reputation: 13

Delete duplicate entries in Ruby

What is the command for deleting duplicate elements in an array? This is my best try:

my_array.reject.with_string{s.clone}

Upvotes: 0

Views: 116

Answers (2)

Amanze
Amanze

Reputation: 298

If you want an array of unique values of my_array = [1, 2, 3, 3, 4], then do this:

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

If your array contains objects with some field that you want to be unique, for example, :fname in:

my_array = [
  {fname: "amanze", age: 28}, 
  {fname: "ben", age: 13}, 
  {fname: "ben", age: 4}
]

then you need to do this:

my_array.uniq { |obj| obj[:fname] }
# =>
# [
#   {fname: "amanze", age: 28}, 
#   {fname: "ben", age: 13}
# ]

Upvotes: 6

Gagan Gami
Gagan Gami

Reputation: 10251

Array#uniq is the best way to find out the uniq records, but as an alternate, you can use Array#&, which returns a new array containing the elements common to the two arrays, excluding any duplicates.

a = [1, 2, 3, 4, 5, 2, 2, 3, 4]
b = a & a
b #=> [1, 2, 3, 4, 5]

Upvotes: 3

Related Questions