Ruby 继承和复制类变量

Ruby 继承和复制类变量,ruby,class,oop,Ruby,Class,Oop,这是一个模拟另一个项目中发生的情况的人为示例。我肯定我只是误解了类的一些基本功能,但我不知道从哪里可以找到答案 如果我在父类中设置了一个实例变量@empty=[],那么我想使用原始实例变量,以及子类中实例变量的变体,我会遇到一个问题,即原始实例变量的原始形式不再可访问 class Parent def initialize @empty = [] end def fill @empty << "foo" #interestingly, changing

这是一个模拟另一个项目中发生的情况的人为示例。我肯定我只是误解了类的一些基本功能,但我不知道从哪里可以找到答案

如果我在父类中设置了一个实例变量
@empty=[]
,那么我想使用原始实例变量,以及子类中实例变量的变体,我会遇到一个问题,即原始实例变量的原始形式不再可访问

class Parent
  def initialize
    @empty = []
  end

  def fill
    @empty << "foo" #interestingly, changing the << to = fixes it, but that's not a possibility on my project
  end
end

class Child < Parent
  def initialize
    super
    @should_still_be_empty = @empty #trying to "make a copy" of the original
  end

  def show_original_variable
    @should_still_be_empty
  end

end

child = Child.new
child.fill #=> ["foo"], which is what it should return
child.show_original_variable #=> ["foo"], I want it to return []
类父类
def初始化
@空=[]
结束
def加注

@emptyDoing
@copy=@original
将对原始对象的引用存储在
@copy
实例变量中

使用
Object#dup
将创建正在分配的对象的浅层副本,并将其存储在实例变量中

class Child 
  def initialize
    @original_empty = []
    @copy_of_empty = @original_empty.dup
  end

  def fill
    @copy_of_empty << "foo"
  end

  def show_empty
    @original_empty
  end

end

child = Child.new
child.fill
#=> ["foo"]
child.show_empty
#=> []
类子类
def初始化
@原始_empty=[]
@复制_of_empty=@original_empty.dup
结束
def加注
@复制_的_empty[“foo”]
child.show_空
#=> []

您的问题与类或继承无关。相反,它处理与赋值变异相关的更基本的问题

xs = [11,22,33]
ys = xs           # Both variables hold a reference to the same data.

zs = xs.dup       # But zs has a copy (at least a shallow copy).

xs << 44          # If we *mutate* xs, ys changes also.

p xs              # [11, 22, 33, 44]
p ys              # [11, 22, 33, 44]
p zs              # [11, 22, 33]

xs = [4,5,6]      # If we *assign* to xs, ys won't be affected.

p xs              # [4,5,6]
p ys              # [11, 22, 33, 44]
xs = [11,22,33]
ys = xs           # Both variables hold a reference to the same data.

zs = xs.dup       # But zs has a copy (at least a shallow copy).

xs << 44          # If we *mutate* xs, ys changes also.

p xs              # [11, 22, 33, 44]
p ys              # [11, 22, 33, 44]
p zs              # [11, 22, 33]

xs = [4,5,6]      # If we *assign* to xs, ys won't be affected.

p xs              # [4,5,6]
p ys              # [11, 22, 33, 44]
@should_still_be_empty = @empty.dup