On 2013-Dec-17, at 15:25 , Johanna Bettina <lists / ruby-forum.com> wrote:

> Hello, can you please help me :)?
> 
> I have an array like this:
> 
> a=[1,-8,4,6]
> 
> there a positive and negative numbers in.
> 
> but now i only want to count the positive.
> 
> So now I have to make a function which returns the number of positive
> numbers (in this time 3). I have tried, but I also managed to count all
> numbers. but I need only to count the positive numbers. And I should do
> it with a loop.
> 
> This is what I got so far:
> 
> def anzahl_positiv(a)
> 
> return a.count
> 
> end
> 
> puts "#{anzahl_positiv(a)}"
> 
> Would be nice if you would help me :). Thank you!
> =======================
> 
> -- 

Count takes a block and only counts the elements for which it is true:

irb1.8.7> a = [ 1, 2, -4, 8 ]
#1.8.7 => [1, 2, -4, 8]
irb1.8.7> a.count
#1.8.7 => 4
irb1.8.7> a.count {|e| e > 0}
#1.8.7 => 3

-Rob

Rob Biedenharn
rob.biedenharn / gmail.com