gpt4 book ai didi

ruby - 在 ruby​​ 中连接它们之间的对象的最佳实践

转载 作者:数据小太阳 更新时间:2023-10-29 08:40:30 24 4
gpt4 key购买 nike

我无法在纯 ruby​​ 脚本中找到一种很好的方法来实现导航轨道对象的轨道行为。

假设我有一个 Parent 类的对象,有一个 Child 类对象数组的访问器,我希望在操作 Child 对象时能够轻松获得 Parent,就像这样:

class Parent
attr_accessor :children

def initialize
@children = Array.new
end
end

class Child
end

parent = Parent.new
first_child = Child.new
second_child = Child.new
parent.children << [ first_child, second_child ]

a_child = parent.children.first

get_parent_from_child = a.child.parent

当然,我感兴趣的部分是最后一行,我试图从其中一个子对象获取“父”对象。

我怎样才能轻松干净地实现它?

我正在考虑为子对象添加访问器,但我不确定每次将子对象附加到父对象时如何确保设置此值。

在 ruby​​ 中是否有一种简单干净的方法来做到这一点?

提前致谢。

最佳答案

您不必完全公开您的 child ,您知道,完全控制对您数据的访问并没有错。

class Parent
def initialize
@children = [ ]
end

# You get a shallow copy of the children, you can
# change the individual children but not the tree
# structure.
def children
@children.dup
end

# We take ownership of the children when you add them.
def add_children(*kids)
kids.each { |k| k.parent = self }
@children += kids
end

def remove_children(&block)
@children.delete_if(&block)
end
end

# This would probably have some sort of payload and
# a sensible "==" implementation.
class Child
attr_reader :parent
def parent=(p)
raise StandardError => 'Not allowed to change parents!' if @parent
@parent = p
end
end

然后 child.parent 工作正常,如果你想删除 child ,你会告诉 parent 删除哪些:

# Remove the children with even payloads.
parent.remove_children { |c| c.payload % 2 == 0 }

# Remove the children with odd payloads and copy them.
odds = [ ]
parent.remove_children do |c|
kill_it = c.payload % 2 != 0
odds << Child.new(c.payload) if(kill_it)
kill_it
end

关于ruby - 在 ruby​​ 中连接它们之间的对象的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7930143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com