2009-06-26 42 views
0

我從named_scope收集的值的特定列如下:如何收集和組合多個數組進行計算?

a = survey_job.survey_responses.collect(&:base_pay) 

這使我例如(1,2,3,4,5)一個數值數組。然後,我可以將這個數組傳遞到我創建的各種函數中,以檢索數字集的均值,中位數和標準差。這一切都正常工作,但我現在需要開始組合多列數據來執行相同類型的計算。

我需要收集或許三個字段的詳情如下:

survey_job.survey_responses.collect(&:base_pay) 
survey_job.survey_responses.collect(&:bonus_pay) 
survey_job.survey_responses.collect(&:overtime_pay) 

這會給我3個陣列。然後,我需要通過將每個匹配值加在一起來將它們組合成單個數組 - 即,添加每個數組的第一個結果,每個數組的第二個結果等等,以便我有一個總數組成的數組。

如何創建一個將所有這些數據收集在一起的方法,以及如何從視圖模板中調用它?

真的很感謝在這一個任何幫助......

感謝

西蒙

回答

0

這裏,將通過採取和各指標在陣列中的任意數量的結合的方法。它將允許每個陣列的長度也不同。

def combine(*arrays) 
    # Get the length of the largest array, that'll be the number of iterations needed 
    maxlen = arrays.map(&:length).max 
    out = [] 

    maxlen.times do |i| 
    # Push the sum of all array elements at a given index to the result array 
    out.push(arrays.map{|a| a[i]}.inject(0) { |memo, value| memo += value.to_i }) 
    end 

    out 
end 

然後,控制器,你可以做

base_pay = survey_job.survey_responses.collect(&:base_pay) 
bonus_pay = survey_job.survey_responses.collect(&:bonus_pay) 
overtime_pay = survey_job.survey_responses.collect(&:overtime_pay) 

@total_pay = combine(base_pay, bonus_pay, overtime_pay) 

,然後根據需要在您的視圖是指@total_pay

+0

我在報告的主循環中進行計算,我通過survey_jobs循環,並且需要爲集合中的每個survey_job執行一組計算。得到一個錯誤: NameError在Admin/surveysController#show 未定義的局部變量或方法`survey_job'爲# 我誤解我該如何在控制器中應用此代碼? – simonyoung 2009-06-26 20:49:38

2
s = survey_job.survey_responses 
pay = s.collect(&:base_pay).zip(s.collect(&:bonus_pay), s.collect(&:overtime_pay)) 
pay.map{|i| i.compact.inject(&:+) } 

這樣做,但具有有意義的變量名稱,我認爲它會工作。

定義在應用程序/助手/ _helper.rb常規方法,它會在視圖中工作

編輯:現在它的工作原理是當它們含有nil或者具有不同的尺寸(只要最長陣列是其中一個郵政編碼被調用

+0

請注意,如果您的數組大小不一樣或者它們包含nil,則此方法將不起作用。 – 2009-06-26 15:19:57