[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[dennou-ruby:000099] Re: deep copy



���Ȥ���Ǥ�

In message "[dennou-ruby:000098] deep copy"
    on 99/09/23, Takeshi Horinouchi <horinout@xxxxxx> writes:

>dup �ä� shallow �ʥ��ԡ��Ǥ���͡�deep �ʥ��ԡ���Ȥ���ˡ�Ϥʤ�

�����Ǥ��͡��Ȥ߹��ߤǤϤʤ��Ǥ�������Ū�ˤ���ߤ˻��Ȥ�����
���⤢�뤫�� deep copy ���񤷤���������Ū�� copy ����ʤ�
Method �Τ褦�ʥ��֥������Ȥ⤢��Τǡ��������Х��������Ǻ�
��ʤ��Ȥ����ʤ��Ǥ��礦��

>�Ǥ��礦�������� deep �Ǥʤ����ɤ��ư��ؤ������Ĥޤꡢľ�ܤΥ���
>�������ѿ��˴ؤ��Ƥ��� dup ���Ƥ����Ф����ΤǤ�����
>
>��ʬ��
>
>  instance_variables.each{|i| i=org.i.dup}
>
>�ߤ����ʴ����Ǥ�(���Τޤޤ����������ܤ�����)��

���ѤΤ����ꡢ���饹���Ȥ˼���Υ��ԡ��᥽�åɤ��դ�����
�����ڤ��⡣���Ѥʤ餳��ʴ������ʤ�������������ƥʤˤ��б�
���Ƥޤ���

module DeepCopieable
  def deep_copy
    res = self.dup
    instance_variables.each{|v| 
      res.instance_eval "#{v} = #{v}.clone" 
    }
    res
  end
end

class Foo
  include DeepCopieable
  attr_accessor :a, :b
end

foo = Foo.new
foo.a = "helo"
foo.b = ["hi"]
bar = foo.deep_copy
p [foo.a.id, bar.a.id] # id returns an unique value for each objects
p [foo.b[0].id, bar.b[0].id]  # containers are not supported

-- gotoken