Removing identical objects in Ruby?

I'm currently writing a Ruby application that is going to search for twitter for various things. One of the problems I ran into is the overall results between searches in close proximity to each other in time. The results are returned to an array of objects, each of which is one tweet. I know the Array.uniq method in ruby ​​that returns an array with duplicates removed.

My question is that. Does the uniq method remove duplicates because these objects point to the same space in memory or that they contain identical information?

If the first, the best way to remove duplicates from an array based on their contents?

+5
source share
4 answers

Does the uniq method remove duplicates because these objects point to the same space in memory or that they contain identical information?

The method is based on the method eql?, so it removes all elements, where is a.eql? (b) returns true. The exact behavior depends on the specific object you are dealing with.

Lines, for example, are considered equal if they contain the same text, regardless of whether they have the same memory allocation.

a = b = "foo"
c = "foo"

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

This is true for most core objects, but not for ruby ​​objects.

class Foo
end

a = Foo.new
b = Foo.new

a.eql? b
# => false

Ruby recommends that you redefine the operator ==depending on your class context.

In your particular case, I would suggest creating an object representing the twitter result and implement the comparison logic so that Array.uniq will behave as you expect.

class Result

  attr_accessor :text, :notes

  def initialize(text = nil, notes = nil)
    self.text = text
    self.notes = notes
  end

  def ==(other)
    other.class == self.class &&
    other.text  == self.text
  end
  alias :eql? :==

end

a = Result.new("first")
b = Result.new("first")
c = Result.new("third")

[a, b, c].uniq
# => [a, c]
+10

-, , , , , Ruby ( , 1.9.3), Array.uniq , #hash, .eql? ==.

+6

uniq eql?, .

. ==, equal? eql?.

+2

, Array.uniq eql? == , , ( , eql? ).

0

All Articles