Fixed typo.
Simplified code by replacing .each with .each_with_index.
Explicitly closing connection to database and some minor refactoring.
Minor refactoring.