我必须组装一些庞大的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级别上,但是我们有引用。因此,您可以使用真实的哈希而不是"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']
,因为leaf
,tree[0][1]
和tree[0][6]
都引用相同的基础哈希。