在Ruby中,您能否将指向节点的点存储在哈希中以供以后替换

问题描述 投票:0回答:1

我必须组装一些庞大的JSON负载,并且我想避免大量重复嵌套的叶子。我想做的是这样的:

tree = {}
tree[0] = {}
tree[0][1] = "stub"

# now save this pointer for later
stub = &tree[0][1]

...

# now go get the leaf

leaf = {0 => ["a","b","c"}

# now without having to search the entire tree, just use the old stub pointer

stub = leaf

可以在Ruby中完成吗?

感谢您的帮助,凯文

ruby pointers hash
1个回答
0
投票

我们没有指针(至少没有在Ruby级别上,但是我们有引用。因此,您可以使用真实的哈希而不是"stub"字符串:

tree = {}
tree[0] = {}
tree[0][1] = {}

然后隐藏在leaf中引用的那个位置:

leaf = tree[0][1]

并修改leaf的内容,而不给leaf分配任何新内容:

leaf[0] = %w[a b c]

根据需要,您将tree[0][1]设置为{0 => ['a', 'b', 'c']}。当然,如果您说leaf = {0 => %w[a b c]},那么您将获得一个新的引用,并且将使用tree[0][1]断开连接。

通常,这朝另一个方向发展。当需要新叶子时,可以创建它:

leaf = {0 => %w[a b c]}

然后将那片叶子放在树上:

tree[0][1] = leaf
tree[0][6] = leaf # Possibly in multiple places

然后您可以说leaf[11] = %w[x y z]tree[0][1][11]tree[0][6][11]也将是['x', 'y', 'z'],因为leaftree[0][1]tree[0][6]都引用相同的基础哈希。

© www.soinside.com 2019 - 2024. All rights reserved.