Array Number of Leaves

Dear Rubyist,

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?
res = 0
self.each{|elem|
if elem.kind_of?(Array)
res += elem.sum_of_array
else
res += elem
end
}
return res
end

def number_of_leaves
self.inject(0){|acc,x|
if x.kind_of?(Array)
acc += x.number_of_leaves
else
acc += x
end
}
end

many thanks in advance.

regards,
salai

2009/10/26 salai [email protected]:

Dear Rubyist,

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.

Cheers

robert

Robert K. wrote:

2009/10/26 salai [email protected]:

Dear Rubyist,

I want to count array list [1,2,3,[4],5] —> # 5 leaves

Out of sheer curiosity… [1,2,3,[4],5].size # → 5
Not what you need?

Hi,

Am Montag, 26. Okt 2009, 21:17:17 +0900 schrieb Robert K.:

   end
 }

I prefer doing it with `case’. I admit I did no performance check.

inject( 0) { |acc,x|
acc += case x
when Array then x.number_of_leaves
else 1
end
}

Bertram

Thankyou verymuch.

regards,
salai.

puts [1,2,3,[4,99],5,7].number_of_leaves #–> 7

On Mon, Oct 26, 2009 at 1:26 PM, salai [email protected] wrote:

puts [1,2,3,[4,99],5,7].number_of_leaves #–> 7

irb(main):001:0> [1,2,3,[4,5,6],7].flatten.size
=> 7

Jesus.

2009/10/26 Bertram S. [email protected]:

The line above should read acc += 1. You could even simplify that as
when Array then x.number_of_leaves
else 1
end
}

You’re right, the solution with “rescue” is rather hackish. :slight_smile:

My serious solution would be

acc += Array === x ? x.number_of_leaves : 1

I prefer to use case for cases (sic!) which have more than two
alternatives.

Kind regards

robert