I have an object, tree. tree has a property, tree.elements. tree.elementsis an array containing both elements and possibly other sub-trees, which in turn will have their own elements array, and so on.
I need a method which will be able to replace objects in the tree if they are of a certain class. The problem is replacing elements inline.
Obviously, the following will not work:
[1,2,3].each { |n| n = 1 }
# => [1,2,3]
But, this will:
a = [1,2,3]
a.each_with_index { |n, idx| a[idx] = 1 }
# => [1,1,1]
However, I am using a recursive function to loop through, and replacing placeholders with content, like so:
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
Keeping track of the indices is really complicated. I’ve tried e.replace("some new content"), but that doesn’t work. What’s the best way to go about this?
I would create a new array rather than trying to update in-place. Something along these lines should work: