我觉得他需要的是 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
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 了两次?
* 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 都可以用