如何为ruby中的每个内部double数组添加哈希键值对?
- 内容介绍
- 文章标签
- 相关推荐
本文共计279个文字,预计阅读时间需要2分钟。
从.xlsx文件中读取数据,并存储为散列和数组。结果如下:
pythonpoetry_at={ 'title': ['诗名1', '诗名2', '诗名3'], 'body': ['诗体1', '诗体2', '诗体3'], 'author': ['作者1', '作者2', '作者3']}
值为: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}
本文共计279个文字,预计阅读时间需要2分钟。
从.xlsx文件中读取数据,并存储为散列和数组。结果如下:
pythonpoetry_at={ 'title': ['诗名1', '诗名2', '诗名3'], 'body': ['诗体1', '诗体2', '诗体3'], 'author': ['作者1', '作者2', '作者3']}
值为: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}

