Select array elements that make up more than 5% of the total

sum = @products.inject(0){ |sum,item| sum += item['count'] }
@selected = @products.select { |item| (item['count']/sum) >= 0.05 }

I want to select each element from an array @productswhose property countis more than 5% of sum. @products- an array of hashes.

However, when I use this second line, @selected returns an empty array. Not finding any errors in |item|or in the array itself @products, I am inclined to believe that it has something to do with trying to use an external variable suminside the block .select. Can someone explain to me why @selectedit returns nothing?

+4
source share
2 answers

If countare integers, item['count']/sumit will always be zero due to integer division.

:

@selected = @products.select { |item| item['count'] >= 0.05 * sum }
+2

:

 @selected = @products.select { |item| (item['count'].to_f/sum) >= 0.05 }

item['count'], sum , . , PRY

(arup~>~)$ pry --simple-prompt
>> 12/13
=> 0
>> 12/13.to_f
=> 0.9230769230769231
>> 12.to_f/13
=> 0.9230769230769231
>> 
+3

Source: https://habr.com/ru/post/1530129/


All Articles