新手问题 求教大神数组内对象不重复 (已解决)

zhq_zhq · 2014年04月04日 · 最后由 arthurymp 回复于 2014年04月10日 · 2415 次阅读

[#, #

Array#uniq
Array#uniq!

是不是学要重载==来确定是否重复呢?

#2 楼 @pynix #1 楼 @willmouse

我觉得他需要的是 ActiveRecord::QueryMethods 的 distinct 方法,只是问的不太好,因为他数组里面看起来像 AR 对象。

User.select(:name)
# => Might return two records with the same name

User.select(:name).distinct
# => Returns 1 record per distinct name

User.select(:name).distinct.distinct(false)
# => You can also remove the uniqueness

@Victor

740     # Specifies whether the records should be unique or not. For example:
741     #
742     #   User.select(:name)
743     #   # => Might return two records with the same name
744     #
745     #   User.select(:name).distinct
746     #   # => Returns 1 record per distinct name
747     #
748     #   User.select(:name).distinct.distinct(false)
749     #   # => You can also remove the uniqueness
750     def distinct(value = true)
751       spawn.distinct!(value)
752     end
753     alias uniq distinct
754
755     # Like #distinct, but modifies relation in place.
756     def distinct!(value = true) # :nodoc:
757       self.distinct_value = value
758       self
759     end
760     alias uniq! distinct!

alias 过了,一个意思,我倒觉得楼主没考虑那么多。

PS:话说这文档是不是错了?distinct 了两次?

#3 楼 @Victor

经过你的提醒,才发现原来这是个 x-y problem。

#4 楼 @willmouse distinct(false) 是拿回“未 distinct”的結果,也就是 :name 字段所有不重複的結果。

匿名 #7 2014年04月06日

为什么你们都能看懂楼主这个问题。。。

如果是要 web_user_id 不重复:

array.uniq_by &:web_user_id

#8 楼 @night_song

* Removed deprecated `Array#uniq_by` and `Array#uniq_by!`, use native
  `Array#uniq` and `Array#uniq!` instead.

4.1 就要删掉了,因为本身 Ruby 的Array#uniq方法就可以接收 block,不过我觉得uniq_by这个名字还是比uniq更适合在后面接 block。

@willmouse @pynix @night_song 感谢你们的解答 arry.uniq 和 array.uniq_by &:web_user_id 都可以用

#7 楼 @dorentus 可能因为他们遇到过同样的需求。。。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号