Adding hash to an array inside double for each

Viewed 42

I am reading some values from an .xlsx file. The values are: column1 = title, column2 = body, column3 = author. I am able to read these values correctly. However, I want to store these value in a hash, and each hash inside an array.

The outcome I would like:

poetry_attributes = [
  {
    title: 'title1',
    author: 'author1',
    body: 'body1',
  },
  {
    title: 'title2',
    author: 'author2',
    body:  'body2',
  }, ....
 ]

However I do not get it.

My code is:

poetry_attributes = []
poetry_attributes_dict = {
    title:         'Title of the poetry',
    body:          'The body of the author',
    author:      'Author of the poetry',
 }

workbook = SimpleXlsxReader.open './db/basic.xlsx'
worksheets = workbook.sheets
worksheets.each do |worksheet|
  num_rows = 0
  worksheet.rows.each do |row|
    row_cells = row
    title = row[0]
    body = row[1]
    author = row[2]
    num_rows += 1
    poetry_attributes_dict[:title] = title
    poetry_attributes_dict[:body] = body
    poetry_attributes_dict[:author] = author
    poetry_attributes << poetry_attributes_dict
 end

end

puts poetry_attributes

I think I am overriding somehow the hash because inside the array is saved only the last hash.

2 Answers

Why would you need an intermediate hash at all?

poetry_attributes << {title: title, body: body, author: author}

Yep, you're using just one single hash object. Adding this single line should solve your problem

num_rows += 1
poetry_attributes_dict = {} # this line
poetry_attributes_dict[:title] = title
Related