Ruby如何为内部每个double数组自动添加唯一哈希值?

2026-04-11 20:221阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计297个文字,预计阅读时间需要2分钟。

Ruby如何为内部每个double数组自动添加唯一哈希值?

我正在从.xlsx文件中读取一些值。这些值包括:column1=title, column2=body, column3=author。我能够正确读取这些值。但是,我想将这些值存储在散列中,并将每个散列存储在数组中。结果我想要的是:`poetry_at`。

Ruby如何为内部每个double数组自动添加唯一哈希值?

我正在从.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}

本文共计297个文字,预计阅读时间需要2分钟。

Ruby如何为内部每个double数组自动添加唯一哈希值?

我正在从.xlsx文件中读取一些值。这些值包括:column1=title, column2=body, column3=author。我能够正确读取这些值。但是,我想将这些值存储在散列中,并将每个散列存储在数组中。结果我想要的是:`poetry_at`。

Ruby如何为内部每个double数组自动添加唯一哈希值?

我正在从.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}