I'm having a hard time understanding why this piece of code works :
def flatten(array, result = [])
array.each do |element|
if element.is_a? Array
flatten(element, result)
else
result << element
end
end
result
end
In particular, why does it work without having to assign the result of the flatten method call to the result array, like so:
def flatten1(array, result = [])
array.each do |element|
if element.is_a? Array
result = flatten(element, result)
else
result << element
end
end
result
end
Both produce the same output:
p flatten [1,2,[3,4,[5,[6]]]] # [1, 2, 3, 4, 5, 6]
p flatten1 [1,2,[3,4,[5,[6]]]] # [1, 2, 3, 4, 5, 6]