From: Morton Goldberg Date: 2007-11-12T13:03:15+09:00 Subject: Re: [noob] name of a variable, at runtime On Nov 11, 2007, at 10:30 PM, Colin Summers wrote: > This seems harder than the usual thing I've been tripping on (and > finding answers in the pickaxe or online). > > I have an object: human. It has parts: human.hand human.foot. > > How can I say this: > fred = human.new > fred.hand = fred.foot = fred. leg = 'flesh' > fred.knee = 'plastic' > fred.head = 'steel' > parts = [hand,foot,leg,knee] > parts.each do |part| > puts "part #{part} is made of " + fred.{part}.to_s > end # with each part > > Am I close? Close, yes, but not quite there. Assuming you want to roll your own Human class, then you can do something like: class Human attr_accessor :hand, :leg, :foot, :head, :knee end fred = Human.new fred.hand = fred.foot = fred.leg = 'flesh' fred.knee = 'plastic' fred.head = 'steel' parts = %w[hand foot leg knee] parts.each do |part| puts "part #{part} is made of #{fred.send(part)}" end OTOH, you might look at the built-in Struct class. It may do everything you want. Regards, Morton