我正在从.xlsx文件中读取一些值. 值为:column1 = title,column2 = body,column3 = author. 我能够正确读取这些值. 但是,我想将这些值存储在散列中,并将每个散列存储在数组中. 结果我想: poetry_at
值为:column1 = title,column2 = body,column3 = author.
我能够正确读取这些值.
但是,我想将这些值存储在散列中,并将每个散列存储在数组中.
结果我想:
poetry_attributes = [ { title: 'title1', author: 'author1', body: 'body1', }, { title: 'title2', author: 'author2', body: 'body2', }, .... ]
但是我没理解.
我的代码是:
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
我想我会以某种方式覆盖哈希,因为在数组中只保存了最后一个哈希.
为什么你需要一个中间哈希?poetry_attributes << {title: title, body: body, author: author}