Dynamic variables in loop I have this working code. I think this must be easier with a while loop.

if not c.e1.nil?
  extrapreis = number_to_currency Extra.find(c.e1).aufschlag, :unit=&gt;"EUR "
  array.push Extra.find(c.e1).name + " (" + extrapreis.to_s + ")"
  extpreis = extpreis + Extra.find(c.e1).aufschlag
end
if not c.e2.nil?
  extrapreis = number_to_currency Extra.find(c.e2).aufschlag, :unit=&gt;"EUR "
  array.push Extra.find(c.e2).name + " (" + extrapreis.to_s + ")"
  extpreis = extpreis + Extra.find(c.e2).aufschlag
end
if not c.e3.nil?
  extrapreis = number_to_currency Extra.find(c.e3).aufschlag, :unit=&gt;"EUR "
  array.push Extra.find(c.e3).name + " (" + extrapreis.to_s + ")"
  extpreis = extpreis + Extra.find(c.e3).aufschlag
end
if not c.e4.nil?
  extrapreis = number_to_currency Extra.find(c.e4).aufschlag, :unit=&gt;"EUR "
  array.push Extra.find(c.e4).name + " (" + extrapreis.to_s + ")"
  extpreis = extpreis + Extra.find(c.e4).aufschlag
end
if not c.e5.nil?
  extrapreis = number_to_currency Extra.find(c.e5).aufschlag, :unit=&gt;"EUR "
  array.push Extra.find(c.e5).name + " (" + extrapreis.to_s + ")"
  extpreis = extpreis + Extra.find(c.e5).aufschlag          
end


It is always the same code, except for the variable e (1, 2, 3, 4, 5). How can I put this in a while loop and put the counter together with e?
(1..5).each do |i|
  e = c.send("e#{i}")
  next if e.nil?
  found = Extra.find(e)
  array.push("#{found.name} (#{number_to_currency(found.aufschlag, unit: "EUR ")})")
  extpreis += found.aufschlag
end


If you can be certain that c.e1 etc. never becomes false, then:

(1..5).each do |i|
  next unless e = c.send("e#{i}")
  found = Extra.find(e)
  array.push("#{found.name} (#{number_to_currency(found.aufschlag, unit: "EUR ")})")
  extpreis += found.aufschlag
end