[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: pulling specific dup. elements out of an array

Brian Candler

8/6/2007 10:15:00 AM

> > why didn't reject work?
> >
> >>> array = ['234234','04593','4098234','0','0','0']
> > => ["234234", "04593", "4098234", "0", "0", "0"]
> >>> array.reject {|e| e == '0' }
> > => ["234234", "04593", "4098234"]
>
> well lemme further explain what im attempting to do and why i couldnt
> get reject to work right, i need to delete all the 0's in the array then
> add up those non-zero numbers.
> with:
>
> array.inject(0) {|num, i| num + i}/array.length/1024 #1024 =
> kilobytes convert
>
> so if theres a way to shove reject into that then lemme know ^^

Just do the reject first (use reject! if you want to modify the array
in-place), and then run your inject on the results of that.

If you prefer to do it all in a single functional-style inject, then I guess
you can do something like this:

array = ['234234','4593','4098234','0','0','0']

sum, len = array.inject([0,0]) { |(sum,len),i|
i != '0' ? [sum+Integer(i),len+1] : [sum,len] }

puts sum / len / 1024