2013-02-13 244 views
1

我有以下的方法實在太長了:傳遞一個對象作爲參數

def combine_atoms 
    @left.each do |chemical| 
    chemical.chem_species.each do |atom| 
     if @left_total[atom[0]].nil? 
     @left_total[atom[0]] = atom[1] 
     else 
     @left_total[atom[0]] += atom[1] 
     end 
    end 
    end 

    @right.each do |chemical| 
    chemical.chem_species.each do |atom| 
     if @right_total[atom[0]].nil? 
     @right_total[atom[0]] = atom[1] 
     else 
     @right_total[atom[0]] += atom[1] 
     end 
    end 
    end 
end 

一個怎麼能忽略@left@left_total作爲參數,使用Ruby減少一半的代碼行數?

回答

3

您可以從combine_atoms方法到一個新的帶有參數這樣的分離循環:

def combine_atoms 
    @left_total = combine_part(@left, @left_total) 
    @right_total = combine_part(@right, @right_total) 
end 

def combine_part(part, total) 
    part.each do |chemical| 
    chemical.chem_species.each do |atom| 
     if total[atom[0]].nil? 
     total[atom[0]] = atom[1] 
     else 
     total[atom[0]] += atom[1] 
     end 
    end 
    end 
end 
相關問題