From: "David A. Black" Date: 2004-08-12T20:20:32+09:00 Subject: Re: getting object attributes Hi -- On Thu, 12 Aug 2004, Sam McCall wrote: > Joe Laughlin wrote: > > > I want to do something similar to this: > > > > class Foo > > @goo = 2 > > @boo = 5 > > end > > > > foo = Foo.new > > > > ["goo", "boo"].each do |attribute| > > puts foo.attribute # should print out 2 on the first loop, 5 on the > > second loop > > end > ["@goo","@boo"].each do |attribute| > puts foo.instance_variable_get attribute > end That will print: nil nil @goo and @boo are instance variables of the Class object Foo, not of its instances. You'd have to do: puts foo.class.instance_variable_get(attribute) or, if you want to be direct: puts Foo.instance_variable_get(attribute) This is one of those times where a Class object, despite being a special thing in various ways, is behaving just like any old object. In fact, it's better to respect that, and not access its instance variables from outside unless it lets you -- which you could do with: class Foo class << self attr_reader :goo, :boo end @goo = 2 @boo = 5 end puts Foo.goo # 2 > > Also: > foo.instance_variables.each do |attribute| > puts foo.instance_variable_get attribute > foo.instance_variable_set nil (You need two arguments for instance_variable_set :-) David -- David A. Black dblack@wobblini.net