ruby - 如何在 Ruby 中为每个 id 创建哈希

标签 ruby hash

我用 Ruby 读取了以下 xls 文件 Roo .

现在我想像这样为每个 studentid 做哈希。

132 = { "Design" => 6, "English" => 5, "Humanities" => 5, .... }
134 = { "Design" => 7, "English" => 6, "Humanities" => 6, .... }
...
...

以下是我所做的。它会输出一些东西,但我需要构建以创建哈希。

require_relative './subcorrelation/version'
require 'linefit'
require 'roo'
myfile='../data/msdataparts.xls'

workbook = Roo::Excel.new(myfile)
workbook.default_sheet = workbook.sheets.first

# Create a hash of the headers so we can access columns by name (assuming row
# 1 contains the column headings).  This will also grab any data in hidden
# columns.
headers = Hash.new
workbook.row(1).each_with_index {|header,i|
headers[header] = i
}

# Iterate over the rows using the `first_row` and `last_row` methods.  Skip
# the header row in the range.
((workbook.first_row + 1)..workbook.last_row).each do |row|
  # Get the column data using the column heading.
  studentid = workbook.row(row)

  puts "{#studentid}"
end

更新

上述线的输出。

[132.0, "Design", 6.0, "MYC665", "S2", 7.0]
[132.0, "English", 5.0, "MYC600", "S2", 7.0]
[132.0, "Humanities", 5.0, "MYC610", "S2", 7.0]
[132.0, "Languages", 6.0, "MYJ660", "S2", 7.0]
[132.0, "Math", 6.0, "MYC620", "S2", 7.0]
[132.0, "Music", 7.0, "MYC664", "S2", 7.0]
[132.0, "PE", 6.0, "MYC650", "S2", 7.0]
[132.0, "Science", 6.0, "MYC630", "S2", 7.0]
[132.0, "Theatre", 6.0, "MYC661", "S2", 7.0]
[134.0, "Design", 7.0, "MYC665", "S2", 7.0]
[134.0, "English", 6.0, "MYC600", "S2", 7.0]
[134.0, "Humanities", 6.0, "MYC610", "S2", 7.0]
[134.0, "Languages", 6.0, "MYS610", "S2", 7.0]
...
...

enter image description here

最佳答案

hash_of_student_and_grades = ((workbook.first_row + 1)..workbook.last_row).each_with_object({}) do |row,hash|
  # Get the column data using the column heading.
  next if workbook.row(row).nil?
  studentid = workbook.row(row)[0]
  course = workbook.row(row)[1]
  grade = workbook.row(row)[2]
  hash[studentid.to_i] ||= {}
  hash[studentid.to_i][course] = grade.to_i
end

puts hash_of_student_and_grades

应该给你你想要的散列。

关于ruby - 如何在 Ruby 中为每个 id 创建哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20740302/

相关文章:

mysql - Ruby、Rake、Mysql - 创建数据库

ruby-on-rails - ruby rails : Convert a path in a string to a recursive Hash

ruby-on-rails - rails 5 : find_or_create_by not saving all the params

ruby - 两个 gem 共享相同的要求?

ruby - 无法使用 RVM 安装 ruby​​ 1.9.2

python - 如何在 Python 中生成混合大小写哈希?

java - 重写toString方法并避免碰撞

android facebook 集成 : invalid key hash

ruby 数组键对值?

ruby-on-rails - 安装mysql(2.9.1)时出错,Bundler无法继续