2015-05-27 43 views
0

我有這樣的功能:調用列表中的相同函數並返回沒有重複的列表?

medIntCategory = MedicalInterventionCategory.find_by_category_text(category.category.text) 

但是現在我有一個名爲類別的類別列表。

我想爲每個類別執行上面的代碼並獲取medIntCategories的列表,但沒有重複。

有沒有簡單的方法來做到這一點,因爲我只處理整數?

簡單來說

categoryList = [] 
for each category in categories do 
categoryList += MedicalInterventionCategory.find_by_category_text(category.category.text) 
end 

但隨着重複檢查

+1

究竟你「我只處理整數」是什麼意思?你是說'MedicalInterventionCategory.find_by_category_text'返回一個整數嗎? – Ajedi32

回答

1

這聽起來像Array#mapArray#uniq工作:

category_list = categories.map{|category| 
    MedicalInterventionCategory.find_by_category_text(category.category.text) 
}.uniq 
0

,我認爲這會工作

category_list = [] 
    categories.each do |category| 
     category_list << MedicalInterventionCategory.find_by_category_text(category.category.text).distinct 
    end 
+0

這是如何處理欺騙? –

1
@result=Array.new 
    ##assuming that it returns an array 
    medIntCategory = MedicalInterventionCategory.find_by_category_text(category.category.text) 
    ##get the first category obtained 
    @result << medIntCategory 
    if medIntCategory.present? 
     medIntCategory.each do |m| 
     ##add in same array only if not present 
     if [email protected]?(m) 
      @result << m.find_by_category_text(c.category.text) 
     end 
     end 
    ##return a unique value array 
    @result.flatten.compact.uniq unless @result.blank? 
    end 

希望它有助於

相關問題