我正在提取CSV数据,然后将其存储为数组。我需要将这些数组作为单个Hash返回。
这将允许我为每个索引使用一个键,而不是使用索引号,但是我遇到了让它运行的问题。它记录一个错误,说明参数数量错误。
我出错的任何想法?
代码:
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
]
答案 0 :(得分:7)
你对此的看法相当困惑。任何时候你看到大量的变量都是一个标志,你应该使用不同的存储方法。你在返回它们之前将它们折叠成一个Hash,这是一个关于它们应该如何存储的暗示。
这是一个更加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
答案 1 :(得分:4)
使用此:
return Hash["ref", ref, "summary", summary, "pri", pri, "state", state,
"estDur", estdur, "notes", notes, "supporter", supporter,
"bz", bz, "project", project, "team", team]
无需hashed
变量。