Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Object | clone

概要

Object#clone -> Class

詳細

オブジェクトの複製を返却。
浅い(shallow)コピー。

サンプルコード
require 'tbpgr_utils'

class Hoge
  attr_reader :str, :arr
  def initialize(str, arr)
    @str, @arr = str, arr
  end
end

hoge = Hoge.new("hoge", [*'a'..'f'])
hoge.taint
def hoge.fuga
end
hoge.freeze
clone_hoge = hoge.clone

str = "A"
clone_str = str.clone

bulk_puts_eval binding, <<-EOS
hoge
clone_hoge
hoge == clone_hoge
hoge.equal?(clone_hoge)
clone_hoge.tainted?
clone_hoge.frozen?
str
clone_str
str == clone_str
str.equal?(clone_str)
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

hoge                    # =>       #<Hoge:0x20bf098 @str="hoge", @arr=["a", "b", "c", "d", "e", "f"]>
clone_hoge              # =>       #<Hoge:0x20beeb8 @str="hoge", @arr=["a", "b", "c", "d", "e", "f"]>
hoge == clone_hoge      # => false
hoge.equal?(clone_hoge) # => false
clone_hoge.tainted?     # => true
clone_hoge.frozen?      # => true
str                     # => "A"
clone_str               # => "A"
str == clone_str        # => true
str.equal?(clone_str)   # => false