Рассмотрите возможность принятия следующей структуры.
class Child
attr_accessor :name # create accessor for name of child
def initialize(name)
@name = name
end
end
class Parent
@families = {} # create class instance variable
class << self # change self to singleton class
attr_reader :families # create accessor for @families
end
def initialize(name, children)
self.class.families[name] = children.map { |name| Child.new(name) }
end
end
Parent.new("Bob and Diane", %w| Hector Lois Rudolph |)
#=> #<Parent:0x00005ac0ddad9aa0>
Parent.new("Hank and Trixie", %w| Phoebe |)
#=> #<Parent:0x00005ac0ddb252c0>
Parent.new("Thelma and Louise", %w| Zaphod Sue |)
#=> #<Parent:0x00005ac0ddcb2890>
Parent.families
#=> {"Bob and Diane" =>[#<Child:0x00005ac0ddadf9f0 @name="Hector">,
# #<Child:0x00005ac0ddadf388 @name="Lois">,
# #<Child:0x00005ac0ddadf1a8 @name="Rudolph">],
# "Hank and Trixie" =>[#<Child:0x00005ac0ddb251d0 @name="Phoebe">],
# "Thelma and Louise"=>[#<Child:0x00005ac0ddcb27c8 @name="Zaphod">,
# #<Child:0x00005ac0ddcb27a0 @name="Sue">]}
Parent.families.keys
#=> ["Bob and Diane", "Hank and Trixie", "Thelma and Louise"]
Parent.families["Bob and Diane"].map { |child| child.name }
#=> ["Hector", "Lois", "Rudolph"]