From: Mikael Brockman Date: 2004-08-16T22:29:26+09:00 Subject: Re: returning symbols Daniel Cremer writes: > I want to write a method to store a list of some instance variables in > an Array that will later be run through to access their data. Normally > in another language I would do this by passing them by reference when I > store them into the Array. > > Using the object_id doesn't work because that's to the object the > variable is pointing to and this may change. > So, to sum it up: > > Is there a way to get variables to return their symbol so you can access > what they will be referencing in the future ? > > thanks, > Daniel It's kind of a hack, and you should avoid using it, but | class Box | def initialize (&accessor) | @accessor = accessor | end | | def set! (new) | @accessor.call new | end | | def get | @accessor.call | end | end | | class Object | def box (variable) | Box.new do |*value| | if value.empty? | instance_variable_get variable | else | instance_variable_set variable, value.first | end | end | end | end > foo = Foo.new => # > box = foo.box(:@a) => #> > box.get => 5 > box.set! 10 => 10 > box.get => 10 > foo.instance_variable_get(:@a) => 10