我有以下方法太长:
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将代码行数减少一半? 最佳答案
您可以将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
关于ruby - 传递一个对象作为参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14848598/