Morton Goldberg
11/12/2007 4:03:00 AM
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:
<code>
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
</code>
OTOH, you might look at the built-in Struct class. It may do
everything you want.
Regards, Morton