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

[dennou-ruby:000100] Re: deep copy



���Ȥ���Ǥ�

In message "[dennou-ruby:000099] Re: deep copy"
    on 99/09/24, GOTO Kentaro <gotoken@xxxxxx> writes:
>���ѤΤ����ꡢ���饹���Ȥ˼���Υ��ԡ��᥽�åɤ��դ�����
>�����ڤ��⡣���Ѥʤ餳��ʴ������ʤ�������������ƥʤˤ��б�
>���Ƥޤ���

Marshal ��Ȥ��Ȥ������פ������ޤ���������ʤ���߻��Ȥ�Ф�
����ʤϤ��������� Marshal.dump �λ������¤�����ޤ�:

module DeepCopieable
  require "marshal"

  def deep_copy
    # this method uses marshal, so Class, Module, IO, Data and their
    # descendants cannot be copied. 
    r, w = IO.pipe
    Marshal.dump(self, w)
    w.close
    Marshal.load(r)
  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 is unique for each objects
p [foo.b[0].id, bar.b[0].id]  # container is also supported now