gpt4 book ai didi

ruby - 将数组存储为哈希?

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:57 24 4
gpt4 key购买 nike

我正在提取 CSV 数据,然后将其存储为数组。我需要将这些数组作为单个哈希返回。

这将允许我为每个索引使用一个键,而不是使用索引号,但我在让它工作时遇到了问题。它记录一个错误,指出参数数量错误。

有什么地方出错了吗?

代码:

ref       = Array.new
summary = Array.new
pri = Array.new
state = Array.new
estdur = Array.new
notes = Array.new
supporter = Array.new
bz = Array.new
project = Array.new
team = Array.new

hashed = Hash.new

csvPath = "#{File.dirname(__FILE__)}"+"/../modules/csv.csv"
CSV.foreach(csvPath, :headers=>true, :header_converters=>:symbol) do |row|
ref << row [ :feature ]
summary << row [ :Summary ]
pri << row [ :Pri ]
state << row [ :State ]
estdur << row [ :EstDur ]
notes << row [ :Notes ]
supporter << row [ :Supporter ]
bz << row [ :BZ ]
project << row [ :Project ]
team << row [ :Team ]
end
return hashed[
"ref", ref,
"summary", summary,
"pri", pri,
"state", state,
"estDur", estdur,
"notes", notes,
"supporter", supporter,
"bz", bz,
"project", project,
"team", team
]

最佳答案

您处理此问题的方式相当困惑。每当您看到大量这样的变量时,就表明您应该使用不同的存储方法。在返回它们之前将它们折叠成散列是关于它们应该如何存储的提示。

这是一个更像 Ruby 风格的重做:

# Create a Hash where the default is an empty Array
result = Hash.new { |h, k| h[k] = [ ] }

# Create a mapping table that defaults to the downcase version of the key
mapping = Hash.new { |h, k| h[k] = k.to_s.downcase.to_sym }

# Over-ride certain keys that don't follow the default mapping
mapping[:feature] = :ref

csvPath = File.expand_path("/../modules/csv.csv", File.dirname(__FILE__))

CSV.foreach(csvPath, :headers => true, :header_converters => :symbol) do |row|
row.each do |column, value|
# Append values to the array under the re-mapped key
result[mapping[column]] << value
end
end

# Return the resulting hash
result

关于ruby - 将数组存储为哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12842415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com