【发布时间】:2014-03-19 11:34:52
【问题描述】:
我找到了以下代码here 用于消除数组中的重复记录:
require 'set'
class Array
def uniq_by
seen = Set.new
select{ |x| seen.add?( yield( x ) ) }
end
end
我们可以使用上面的代码如下:
@messages = Messages.all.uniq_by { |h| h.body }
我想知道调用该方法时如何以及会发生什么。有人可以解释上面代码的内部吗?在uniq_by 方法中,我们没有做任何事情来处理块参数。 uniq_by 方法如何处理传递的参数?
【问题讨论】:
-
Array.uniq自 Ruby 1.9.3 以来占用了一个块,因此不再需要此代码。