uniq 方法是否删除重复项
只要这些对象指向
内存中的相同空间或它们
包含相同的信息?
该方法依赖于 eql? 方法,因此它会删除 a.eql?(b) 返回 true 的所有元素。
确切的行为取决于您正在处理的特定对象。
例如,如果字符串包含相同的文本,则认为它们是相等的,而不管它们共享相同的内存分配。
a = b = "foo"
c = "foo"
[a, b, c].uniq
# => ["foo"]
这适用于大部分核心对象,但不适用于 ruby 对象。
class Foo
end
a = Foo.new
b = Foo.new
a.eql? b
# => false
Ruby 鼓励您根据您的类上下文重新定义 == 运算符。
在您的具体情况下,我建议创建一个表示 twitter 结果的对象并实现您的比较逻辑,以便 Array.uniq 的行为符合您的预期。
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]