开发者

Ruby - How to reproduce the pointers/references behavior?

开发者 https://www.devze.com 2023-01-08 16:10 出处:网络
I am currently trying to create an engine for a new application. Design is quite complex and i realy need a way to create a re开发者_Python百科ference or a pointer or what ever way to remotely modify

I am currently trying to create an engine for a new application.

Design is quite complex and i realy need a way to create a re开发者_Python百科ference or a pointer or what ever way to remotely modify and access the datas. Datas must be kept in a single place and must not be duplicated.

Is there a way do get an object by reference ? For example can I get the instance of a class with his object_id ?

Thanks for your help ;)


The following should demonstrate how to get a reference to an object and de-reference it:

   s = "I am a string"                    #=> "I am a string"
   r = ObjectSpace._id2ref(s.object_id)   #=> "I am a string"
   r == s                                 #=> true

You may wish to review the documentation for Object and ObjectSpace.


Not sure exactly what you want to achieve. Ruby uses references for all custom objects already.

You may want to look at the delegate library.

require 'delegate'

obj = "foo"
ptr = SimpleDelegator.new(obj)
ptr.upcase # => "FOO"
other_obj = "bar"
ptr.__setobj__(other_obj)  # make ptr point to another object 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号