0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

rubyでインスタンスをcopyしたらインスタンス変数はどうなるのか

Last updated at Posted at 2020-06-11

結論

インスタンス変数もコピーされる

検証

こういうクラスがあったとして

class Test
  def set_name(name)
    @name = name
  end
  def get_name
    @name
  end
end

まずは普通にインスタンス変数を設定

origin = Test.new
=> #<Test:0x00007fcebd06e940>

origin.set_name("origin")
=> "origin"

origin.get_name
=> "origin"

cloneするとインスタンス変数ごとコピーされる

copy = origin.clone
=> #<Test:0x00007fcebd05d7a8 @name="origin">

copy.get_name
=> "origin"

copyの方のインスタンス変数を書き換えても元の方には影響しない

copy.set_name('copy')
=> "copy"

origin.get_name
=> "origin"

dup

dupも同様

copy2 = origin.dup
=> #<Test:0x00007fcebd054040 @name="origin">

irb(main):030:0> copy2.get_name
=> "origin"
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?