From: "Mauricio Fernández" Date: 2003-05-08T06:46:26+09:00 Subject: Re: access a variables name? On Thu, May 08, 2003 at 06:05:15AM +0900, meinrad.recheis wrote: [...] > i want to configure objects with different values from files. > it is possible to configure an object by loading a file and evaluating it's > content inside that object: > > File: configuration.rb > > @var1 = [1,2] > @var2 = {1=>@var1} ... > > after evaluating this files lines inside the object's namespace @var1 and > @var2 do exist as names. > maybe i have an interactive program and the user changes values for @var1 > or @var2. > > now i want to overwrite my configuration.rb with the new values that the > names @var1 and @var2 reference. so that configuration.rb could be > evaluated again. > [...] > saving a hash to a interpretable string is no problem using #inspect > my only problem is saving the names of the object, that are in fact > existent in the namespace. Got it now :-) batsman@tux-chan:/tmp$ expand -t2 ac.rb class Foo def iv_name(iv) instance_variables.each do |x| return x if instance_eval(x).id == iv.id end nil end def dump(var, subst = false) name = iv_name(var) return name if name && subst case var when Array "[" + var.map {|x| self.dump(x,true)}.join(",") + "]" when Hash "{" + var.map {|k, v| self.dump(k,true) + "=>" + self.dump(v,true)}.join(",") + "}" else var.inspect end end end file = <<-EOF @var1 = [1,2] @var2 = {1=>@var1} @var3 = {@var1 => @var2} EOF someobj = Foo.new someobj.instance_eval file puts "Reconstructed file:" someobj.instance_variables.sort.each do |x| repr = someobj.dump(someobj.instance_eval(x)) puts "#{x} = #{repr}" end batsman@tux-chan:/tmp$ ruby ac.rb Reconstructed file: @var1 = [1,2] @var2 = {1=>@var1} @var3 = {@var1=>@var2} You can make it cleaner if you make "dump" (or better find another name so it doesn't conflict with Marshal) an instance method of all the classes involved. But then you have to pass around the object these iv. live in so they can resolve names if needed. That would be more OO and elegant, but probably overkill. Can post this too if you want, but that'll be tomorrow :-) -- _ _ | |__ __ _| |_ ___ _ __ ___ __ _ _ __ | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ | |_) | (_| | |_\__ \ | | | | | (_| | | | | |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_| Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com By golly, I'm beginning to think Linux really *is* the best thing since sliced bread. -- Vance Petree, Virginia Power