I want to count array list [1,2,3,[4],5] —> # 5 leaves
but I always get sum_of_array.
Where did I do wrong?
def array_leave1 # sum_of_array?
The method should have the same name as the one you call below
(“elem.sum_of_array”).
def number_of_leaves
self.inject(0){|acc,x|
if x.kind_of?(Array)
acc += x.number_of_leaves
else
acc += x
The line above should read acc += 1. You could even simplify that as
acc += (x.number_of_leaves rescue 1)
end
}
end
Not sure what your issue is exactly. Please show the complete code
along with expected results. The code you presented cannot be the
real code because at least the class declaration is missing.