我已经在rails中实现了继承,并从Person类中获取了子孙。
但现在我想使用简单的ruby类从Person类中获取子孙,而不使用ActiveRecord。
我设法从一个人对象中获取孩子。请指导我如何从Person实例中获取孙子。
class Person
attr_accessor :name, :age
attr_reader :ref
def initialize(name, ref)
@name = name
@ref = ref
end
end
class Parent < Person
attr_reader :children
def initialize(names = %w(A B C))
@children = names.map do |n|
Person.new(n, self)
end
end
end
bar = Parent.new.children.first
bar.ref
答案 0 :(得分:2)
如果父,子和granchild之间没有行为差异,那么可以使用一个类建模:
class Person
attr_reader :children
attr_reader :name
def initialize(name, children: [])
@name = name
@children = children
end
def grandchildren
@children.flat_map(&:children)
end
end
我们添加了一个#grandchildren方法,询问每个孩子的孩子。此示例显示了它的工作原理:
sally = Person.new("Sally")
fred = Person.new("Fred", children: [sally])
mary = Person.new("mary", children: [fred])
p mary.children.map(&:name) # => ["Fred"]
p mary.grandchildren.map(&:name) # => ["Sally"]
答案 1 :(得分:1)
让我们通过NameMagic
(gem y_support/name_magic
,gem install y_support
安装)将问题简化为最低要求:
require 'y_support/name_magic'
class Person
include NameMagic
attr_accessor :children
def initialize( children: [] )
@children = Array( children )
end
def grandchildren
children.map( &:children ).flatten.uniq
end
end
现在NameMagic
负责为您命名,同时您负责定义家谱:
Mary = Person.new
Fred, Joe = Person.new, Person.new
Mary.children << Fred << Joe
Sally, Sam = Person.new, Person.new
Fred.children << Sally << Sam
Jane = Person.new
Joe.children << Jane
然后
Mary.grandchildren
#=> [Sally, Sam, Jane]
请注意,y_support/name_magic
允许您仅通过常量赋值来命名对象,并告诉inspect
方法显示名称。它还会自动处理:name
构造函数的new
关键字参数:
Joe.children << Person.new( name: :Mike )
# now Mary has 4 grandchildren
Mary.grandchildren
#=> [Sally, Sam, Jane, Mike]
答案 2 :(得分:0)
你们都比我快。但是,有时孩子会有新的孩子:
suzie = Person.new(name: 'Suzie')
bobby = Person.new(name: 'Bobby')
harriet = Person.new(name: 'Harriet')
suzie.children = [bobby, harriet]
苏西有两个孩子,鲍比和哈丽特:
puts "Suzie has #{suzie.grandchildren.count} grandchildren named #{suzie.grandchildren.map(&:name)}"
=> Suzie has 0 grandchildren named []
但是,可怜的苏西没有孙子:
ralph = Person.new(name: 'Ralph')
madge = Person.new(name: 'Madge')
bea = Person.new(name: 'Bea')
bobby.children = [ralph]
harriet.children = [madge, bea]
但是,那小小的祝福来了:
puts "Suzie has #{suzie.grandchildren.count} grandchildren named #{suzie.grandchildren.map(&:name)}"
Suzie has 3 grandchildren named ["Ralph", "Madge", "Bea"]
现在Suzie是一个快乐的奶奶:
johnny = Person.new(name: 'Johhny')
bobby.children = [johnny]
puts "Suzie has #{suzie.grandchildren.count} grandchildren named #{suzie.grandchildren.map(&:name)}"
=> Suzie has 4 grandchildren named ["Ralph", "Johhny", "Madge", "Bea"]
Bobby不停地来:
{{1}}
感谢Wayne for flat_map!