争论改变搞乱代码

时间:2015-08-21 23:15:28

标签: arrays ruby immutability

调用第二个方法时,初始方法的参数rec1rec2会被更改,而fourpoints(矩形的两个角的数组)会意外地被更改改变。

def rec_inter(rec1, rec2)
  foursides1 = []
  foursides2 = []
  fourpoints = rec1 + rec2
  p fourpoints
  points(rec1, foursides1)
  points(rec2, foursides2)
  crossing = foursides1 & foursides2
  # want to  do -> crossing & fourpoints <- to get intersections 
  p crossing
  p fourpoints #changes due to points method, how do I fix
end
def points(corners, rec)
  while corners[0][0] <= corners[1][0]
    rec << [corners[0][0], corners[0][1]]
    corners[0][0] = (corners[0][0] + 1)
  end
  while corners[0][1] <= corners[1][1]
    rec << [corners[1][0], corners[1][1]]
    corners[0][1] = (corners[1][0] + 1)
  end
  first = rec.flatten[0]
  while corners[1][0] >= first
    rec << [corners[1][0], corners[1][1]]
    corners[1][0] = corners[1][0] - 1
  end
  rec.uniq!
end

#rec1 & rec2 == cross refernce
rec_inter([[0, 0], [2, 1]], [[1, 0], [3, 1]])

有没有办法将这些值存储到代码执行时未被更改的变量中?

1 个答案:

答案 0 :(得分:1)

您的net/sftp数组发生变化的原因是因为fourpointsrec1是二维数组,这意味着ruby不会复制数组中的数组。

这可以通过以下方式看出:

rec2

为了解决此问题,您需要深度复制数组

pry(main)> ary = [[1,2]]
=> [[1, 2]]
pry(main)> ary2 = [[3,4]]
=> [[3, 4]]
pry(main)> f = ary + ary2
=> [[1, 2], [3, 4]]
pry(main)> ary[0][0] = 10
=> 10
pry(main)> f
=> [[10, 2], [3, 4]]

然后,您就可以修改fourpoints = [] rec1.each { |a| fourpoints << a.dup } rec2.each { |a| fourpoints << a.dup } rec1,而不会影响rec2

深度复制数组的另一种方法是使用fourpointsMarshal::load

Marshal::dump