更新时间:2023-02-22 12:56:31
我不知道你说的合并"是什么意思(数组没有 #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.