sum = @products.inject(0){ |sum,item| sum += item['count'] }
@selected = @products.select { |item| (item['count']/sum) >= 0.05 }
I want to select every element from the @products
array whose count
property is greater than 5% of the sum
. @products
is an array of hashes.
However, when I use this second line, @selected returns an empty array. After finding no fault with |item|
or the @products
array itself, I'm inclined to believe it has something to do with trying to use an external variable, sum
, inside the .select
block. Could someone explain to me why @selected
is returning nothing?
If the count
s are integers, item['count']/sum
will always be zero due to integer division.
Try the following instead:
@selected = @products.select { |item| item['count'] >= 0.05 * sum }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments