Ruby-on-rails Rails 向数组添加元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14766843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails add elements to array
提问by Yogzzz
I have a method to calculated the average for a given set of records:
我有一种方法来计算给定记录集的平均值:
input = params[:recommendation_ratings].values # The params are sent from radio_tags in my view.
input.each do |mini_params|
rating_id = mini_params[:rating_id]
l = Rating.find(rating_id) #Find record on Rating table.
l.rating #Get value associated with rating_id
total_rating = []
total_rating << l.rating
average = total_rating.inject{ |sum, el| sum + el }.to_f / total_rating.size
puts average
end
l.rating is not being appended to the total_rating array. The puts average is being printed as:
l.rating 没有被附加到 total_rating 数组中。看跌期权的平均值被打印为:
3.0
3.0
3.0
3.0
3.0
How do I append each of the ratings being returned to the array to calculated the average,and other math functions.
如何将返回的每个评分附加到数组以计算平均值和其他数学函数。
回答by shweta
try:
尝试:
total_rating = []
input.each do |mini_params|
rating_id = mini_params[:rating_id]
l = Rating.find(rating_id) #Find record on Rating table.
total_rating << l.rating
end
average = total_rating.sum / total_rating.size.to_f
回答by jvnill
this should solve your issue but there is a better way
这应该可以解决您的问题,但有更好的方法
total_rating = []
input.each do |mini_params|
rating_id = mini_params[:rating_id]
l = Rating.find(rating_id) #Find record on Rating table.
total_rating << l.rating
average = total_rating.inject(:+).to_f / total_rating.size
puts average
end
So given an array of ids, try the following
因此,给定一组 id,请尝试以下操作
Rating.where(id: mini_params[:rating_id]).average(:rating)
UPDATE: fixing the one line version
更新:修复单行版本
rating_ids = input.map { |mini_params| mini_params[:rating_id] }
Rating.where(id: rating_ids).average(:rating)
回答by Logan Serman
You need to first get all of the ratings you are trying to average. I'm assuming you have already done this, and all of those ratings are stored in total_rating. Then you need to add the specific rating to that array:
您需要首先获得您试图平均的所有评分。我假设您已经这样做了,并且所有这些评级都存储在total_rating. 然后您需要将特定评级添加到该数组中:
rating_id = mini_params[:rating_id]
l = Rating.find(rating_id)
total_rating << l
average = total_rating.sum.to_f / total_rating.size
puts average

