加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 为每个内部的double数组添加哈希值

发布时间:2020-12-17 01:24:35 所属栏目:百科 来源:网络整理
导读:我正在从.xlsx文件中读取一些值. 值为:column1 = title,column2 = body,column3 = author. 我能够正确读取这些值. 但是,我想将这些值存储在散列中,并将每个散列存储在数组中. 结果我想: poetry_attributes = [ { title: 'title1',author: 'author1',body:
我正在从.xlsx文件中读取一些值.
值为: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}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读