通过封送处理在 Ruby 中克隆不工作

Cloning in Ruby via Marshaling not Working

我正在自学 Ruby 我的一个 classes,无法解决我遇到的错误。注意:我没有要求任何人为我做我的项目;只是想知道是否有人可以给我一些见解

要点:

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 的细微差别却相当困难。我什至尝试像在 union 中那样在 intersection 方法中克隆 self,但这也不起作用。这让我想知道它是否是某种内存问题?

您没有在此处初始化您的集合:

  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

您当前的实现与联合一起工作,因为联合集开始时是一个空集,并接收您向它抛出的每个订阅者。

顺便说一下,我不确定您是否需要在此处进行复制。似乎你可以没有它。但是当然我还没有看到你的全部代码。