我为自己的一个班级自学Ruby,无法解决我遇到过的错误。注意:我不是要求任何人为我做我的项目;只是想知道是否有人能给我这个洞察力
要点:
Set class' deepCopy
方法:
def deepCopy(toCopy)
Marshal.load(Marshal.dump(toCopy))
end
Set class' union
方法(可行):
def union(set2)
# clone the current set into union set
unionSet = Set.new
unionSet.deepCopy(self)
# iterate through set 2 and append all unique elements to union set
set2.subscribers.each do |sub|
if !unionSet.subscribers.include?(sub)
unionSet.subscribers.push(sub)
end
end
unionSet.printSet
end
Set Class' Intersection
方法(这不起作用):
def intersection(set2)
intersectionSet = Set.new
comparisonSet = Set.new
otherSet = Set.new
# choose the smallest set for the comparison set
if @subscribers.size < set2.subscribers.size
comparisonSet.deepCopy(self)
otherSet.deepCopy(set2)
else
comparisonSet.deepCopy(set2)
otherSet.deepCopy(self)
end
#PROBLEM: Both statements below print nothing and both say they are empty when checked.
intersectionSet.printSet
comparisonSet.printSet
# iterate through the comparison set and store all commonalities in intersection set
comparisonSet.subscribers.each do |sub|
puts "Looking for #{sub}"
if otherSet.subscribers.include?(sub)
intersectionSet.subscribers.push(sub)
end
end
intersectionSet.printSet
end
end
这是一个非常基础的项目,但学习Ruby的细微差别使其变得相当困难。我甚至尝试在self
方法中克隆intersection
,就像我在union
中所做的那样,但这也不起作用。这让我想知道它是否存在某种内存问题?
答案 0 :(得分:0)
您没有在此初始化您的设置:
if @subscribers.size < set2.subscribers.size
comparisonSet.deepCopy(self)
otherSet.deepCopy(set2)
else
comparisonSet.deepCopy(set2)
otherSet.deepCopy(self)
end
未将返回的值分配给集合。它应该是comparisonSet = self.deepCopy(self)
之类的东西。您可以在此处看到方法调用具有冗余信息。我建议您将#deepCopy
更改为
def deep_copy # use snake case as per ruby convention
Marshal.load(Marshal.dump(self))
end
然后你可以做类似的事情:
comparison_set = self.deep_copy
other_set = set2.deep_copy
您当前的实现与union一起使用,因为union set以空集开始,并接收您抛出的每个订阅者。
顺便说一句,我不确定你是否需要在这里复制。似乎你可以没有它。但我当然没有看到你的整个代码。