1

我正在提取 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
]
4

2 回答 2

7

你这样做的方式相当混乱。任何时候你看到大量这样的变量都表明你应该使用不同的存储方法。在返回它们之前将它们折叠成一个哈希是关于它们应该如何存储的提示。

这是一个更加 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
于 2012-10-11T15:04:58.500 回答
4

用这个:

return Hash["ref", ref, "summary", summary, "pri", pri, "state", state, 
            "estDur", estdur, "notes", notes, "supporter", supporter, 
            "bz", bz, "project", project, "team", team]

不需要hashed变量。

于 2012-10-11T14:56:36.933 回答