Wednesday, 15 September 2010

Convert Ruby Array into average -



Convert Ruby Array into average -

say have array such:

array = [["male", 59], ["female", 31], ["unknown gender", 38]]

the number within array total number of users gender. need each element of array , find average each male, female , unknown , set them new array looks this:

new_array = [["male", 46], ["female", 24], ["unknown gender", 30]]

where 2nd value within tuple average.

i have tried setting such:

new_array = [] sum = 0 array.each |k,v| sum += v new_array << [k,(v/sum)*100] end

my new array turns out [["male", 100], ["female", 0], ["unknown gender", 0]]

ive tried few different things , cannot figure out im doing wrong. help great.

there 2 issues here.

the first doing integer partition @ (v/sum). result of not expect, should turn v float: (v.to_f/sum).

the sec problem using sum variable before actually contains sum.

putting these 2 together:

array = [["male", 59], ["female", 31], ["unknown gender", 38]] new_array = [] sum = 0 # calculating sum before it's used in partition below. array.each { |_, v| sum += v } array.each |k, v| new_array << [k, ((v.to_f / sum) * 100).round] end # => [["male", 46], ["female", 24], ["unknown gender", 30]]

ruby arrays

No comments:

Post a Comment