在嵌套块中查找匹配项

时间:2017-04-12 23:39:15

标签: ruby-on-rails arrays ruby

我有一个dates数组和一个对象tests,由用户提交:

dates = []
today = Date.today + 1
(today - 31..today).each{|date| dates.push(date.to_s)}
tests = company.tests.where(date: today - 31..today).order(date: :asc)

我正在迭代每个date,如果有testdate匹配,我会将其添加到score数组中。可能有多个,因此average计算。

score = []
array = []
dates.each do |r|
  tests.each do |t|
    if t.date.strftime("%Y-%m-%d") == r
      score.push(t.security_percentage)
    end
  end
  average = score.reduce(:+).to_i / score.size
  array.push(average)
end

如果没有针对给定日期的任何测试,我很难弄清楚如何插入0。我希望array有31个条目:

[0, 98, 89, 99, 0, 0, ...]

但它只有20个条目,因为我只有20个测试。

2 个答案:

答案 0 :(得分:0)

  

如果没有任何问题,我会试图弄清楚如何插入0   对给定日期的测试。

完成代码后,您可以根据需要推送尽可能多的零:

(1..31-array.size).each do |x|
  array.push(0)
end

这不是很漂亮,但回答了我猜的问题

  

如果没有针对给定日期的测试,我只需要推送它们   目前正在迭代。

这个怎么样:

if t.date.strftime("%Y-%m-%d") == r
  score.push(t.security_percentage)
else
  score.push(0)
end

答案 1 :(得分:0)

了解了如何使用.select

dates = []
array = []
today = Date.today + 1
tests = company.tests.where(date: today - 31..today).order(date: :asc)
(today - 31..today).each{|date| dates.push(date.to_s)}
  dates.each do |r|
    score = []
    matches = tests.select{ |t| t.date.strftime("%Y-%m-%d") == r }
    if matches.length > 0
      matches.each do |m|
        score.push(m.security_percentage)
      end
      average = score.reduce(:+).to_i / score.size
      array.push(average)
    else
      array.push(0)
    end
  end