如何将键值相同的CSV行转化为哈希值?

问题描述 投票:0回答:1

我已经解析了.csv文件,并收到以下标题。

"Date":"Start" "Date":"Due" "Amount":"Total" "Amount":"Left"

每一个都有值。我需要用以下方式将其动态映射为哈希。

{date => {start: value, due: value}, amount => {total: value, left: value}}

请你给我一个建议 我试过用它作为一个数组,比如。

[["Date", "Start"], ["Date", "Due"], ["Amount", "Total"], ["Amount", "Left"]]

然后...

.each_slice(2)

但之后我就卡住了。先谢谢你

ruby-on-rails hash
1个回答
1
投票

你可以尝试一些类似的东西。

rows.map do |row|
  { 
    date: { start: row[1], end: row[3] },
    amount: { total: row[4], left: row[6] }
  }
end

1
投票

Given:

headers = [["Date", "Start"], ["Date", "Due"], ["Amount", "Total"], ["Amount", "Left"]]
values= [1, 2, 3, 4]
Hash[headers.zip(values)].each_with_object({}) do |(keys, value), memo|
  pk = keys.first.downcase.to_sym
  memo[pk] ||= {}
  memo[pk][keys.last.downcase.to_sym] = value
end

输出:

=> {:date=>{:start=>1, :due=>2}, :amount=>{:total=>3, :left=>4}}
© www.soinside.com 2019 - 2024. All rights reserved.