如何在 ruby/rails 中合并两个列表并删除重复项? [英] How do I merge two lists, and remove duplicates, in ruby/rails?
问题描述
我有一个源对象
class Source
def ==(other)
return false if self.url == nil || other == nil
self.url == other.url
end
我有以下几点:
def self.merge_internal_and_external_sources(sources=[], external_sources=[])
(sources + external_sources).uniq
end
我想合并这两个列表,并开始从 external_sources 中剔除源列表中已经存在的项目.我不知道如何雄辩地做到这一点?
I would like to merge the two lists, and start kicking out items from external_sources if they already exist in sources list. I am not sure how to do this eloquently?
我也试过:
sources | external_sources
但这产生的结果没有删除重复项,因为我的 == 比较想要在内部比较 'url' 属性?例如:
but this yields a result without the duplicates being removed because of my == comparison want to compare the 'url' attribute internally? For example:
[src1] == [src2] # true
list = [src1] | [src2]
list.size # 2
推荐答案
我不知道你说的合并"是什么意思(数组没有 #merge
方法,只有散列),但您可以像这样简化代码:
I am not sure what do you mean by "merge" (there is no #merge
method on arrays, only on hashes), but you can simplify your code like this:
merged = sources | external_sources
要使其与您的类一起工作,您还需要两个方法:#hash
(实例哈希值,用于初步相等性筛选)和 #eql?
,用于确认相等:
To make it work with your class, you need two more methods: #hash
(instance hash value, used for preliminary equality screening), and #eql?
, used to confirm equality:
class Source
def hash
url.hash + 1
end
# Or delegate it to the url:
# require 'active_support/core_ext/module/delegation'
# delegate :hash, to: :url
def eql? other
return false if url.nil? || other.url.nil?
url == other.url
end
end
#hash
和 #eql?
是每个类都应该具备的基本工具.添加这些之后,#|
和 #&
方法将开始在 Source
实例的数组上运行.
#hash
and #eql?
are among the basic facilities every class should have. After adding these, #|
and #&
methods will start to behave on arrays of Source
instances.
这篇关于如何在 ruby/rails 中合并两个列表并删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!