gpt4 book ai didi

Ruby递归替换数组

转载 作者:太空宇宙 更新时间:2023-11-03 17:57:11 26 4
gpt4 key购买 nike

我有一个对象,tree 有一个属性,tree.elementstree.elements 是一个包含元素和可能的其他子树的数组,这些子树又将有自己的 elements 数组,依此类推。

我需要一个方法来替换树中属于某个类的对象。问题在于替换内联元素。

显然,下面的方法是行不通的:

[1,2,3].each { |n| n = 1 }
# => [1,2,3]

但是,这将:

a = [1,2,3]
a.each_with_index { |n, idx| a[idx] = 1 }
# => [1,1,1]

但是,我使用递归函数循环遍历,并用内容替换占位符,如下所示:

def replace_placeholders(elements)
elements.each do |e|
if e.respond_to?(:elements) and e.elements.any?
replace_placeholders(e.elements)
elsif e.is_a? Placeholder
e = "some new content" # << replace it here
end
end
end

跟踪索引非常复杂。我试过 e.replace("some new content"),但这不起作用。解决此问题的最佳方法是什么?

最佳答案

我会创建一个新数组,而不是尝试就地更新。按照这些思路应该可以工作:

def replace_placeholders(elements)
elements.map do |e|
if e.respond_to?(:elements) and e.elements.any?
e.elements = replace_placeholders(e.elements) # replace array
e # return e itself, so that map works correctly.
elsif e.is_a? Placeholder
"some new content"
end
end
end

关于Ruby递归替换数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11324201/

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