Reputation: 21907
I have the following method that is just too long:
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
How could one pass @left
and @left_total
as arguments, to reduce the number of lines of code in half using ruby?
Upvotes: 1
Views: 72
Reputation: 9167
You can separate a loop from combine_atoms
method to a new one with arguments like this:
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
Upvotes: 3