From: mark sparshatt Date: 2004-08-13T06:00:19+09:00 Subject: Re: getting object attributes Joe Laughlin wrote: >David A. Black wrote: > > >>Hi -- >> >>On Thu, 12 Aug 2004, 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 >>> >>> >>>Ideas? >>> >>> >>Clarification requested: >> >>Do you want instances of foo to be able to get access to >>the instance variables of Foo itself? Or do you want >>instances of Foo (such as foo) to have their own >>instances variables called @goo and @boo, and reader >>methods to access them? You could do a bunch of >>different variations on this but I'm not sure which >>scenario you're trying to implement. >> >> >>David >> >> > >The second one, I believe. > > > > > then this will do what you want class Foo attr_reader :goo, :boo def initialize() @goo = 2 @boo = 5 end end foo = Foo.new ["goo", "boo"].each do |attribute| puts foo.send(attribute) # should print out 2 on the first loop, 5 on the second loop end @goo and @boo need to be initialised within a method or else they're instance variables of Foos metaclass rather than Foo itself. -- Mark Sparshatt