Rails将元素添加到数组中

时间:2013-02-08 06:21:10

标签: ruby-on-rails ruby

我有一种方法来计算给定记录集的平均值:

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附加到total_rating数组。看跌期权平均值打印为:

3.0
3.0
3.0
3.0
3.0

如何将返回的每个等级附加到数组以计算平均值和其他数学函数。

3 个答案:

答案 0 :(得分:4)

尝试:

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

答案 1 :(得分:2)

这应该可以解决您的问题,但有更好的方法

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

因此,给定一组id,请尝试以下

Rating.where(id: mini_params[:rating_id]).average(:rating)

更新:修复单行版本

rating_ids = input.map { |mini_params| mini_params[:rating_id] }
Rating.where(id: rating_ids).average(:rating)

答案 2 :(得分:0)

您首先需要获得所有您想要平均的评分。我假设您已经完成了此操作,并且所有这些评分都存储在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