Tbpgr Blog

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

Ruby | ObjectSpace | _id2ref

概要

ObjectSpace#_id2ref(id) -> object

詳細

オブジェクト ID(Object#__id__)からオブジェクトを取得

サンプルコード
require 'tbpgr_utils'

Person = Struct.new(:name, :age)
tanaka = Person.new('tanaka', 34)

hoge = "hoge"

bulk_puts_eval binding, <<-EOS
ObjectSpace._id2ref(hoge.__id__)
ObjectSpace._id2ref(tanaka.__id__)
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

ObjectSpace._id2ref(hoge.__id__)   # => "hoge"
ObjectSpace._id2ref(tanaka.__id__) # =>        #<struct Person name="tanaka", age=34>