通过Marshaling无法工作在Ruby中克隆

时间:2017-09-17 22:11:46

标签: ruby marshalling deep-copy

我为自己的一个班级自学Ruby,无法解决我遇到过的错误。注意:我不是要求任何人为我做我的项目;只是想知道是否有人能给我这个洞察力

要点:

  • 存在一个Set类,它有一个Subscriber元素数组
  • Subscriber类读入.csv文件并将新的Subscriber对象推送到Set对象的订阅者数组
  • 我试图找到任意两组的联合和交集
  • 使用编组,我能够使用union方法,但是按照相同的设计,我无法使交叉逻辑工作

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中所做的那样,但这也不起作用。这让我想知道它是否存在某种内存问题?

1 个答案:

答案 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以空集开始,并接收您抛出的每个订阅者。

顺便说一句,我不确定你是否需要在这里复制。似乎你可以没有它。但我当然没有看到你的整个代码。

相关问题