我想解析一个 CSV 文件,以便每一行都被视为一个对象,标题行是对象中属性的名称。我可以写这个,但我确定它已经在那里了。
这是我的 CSV 输入:
"foo","bar","baz"
1,2,3
"blah",7,"blam"
4,5,6
代码看起来像这样:
CSV.open('my_file.csv','r') do |csv_obj|
puts csv_obj.foo #prints 1 the 1st time, "blah" 2nd time, etc
puts csv.bar #prints 2 the first time, 7 the 2nd time, etc
end
使用 Ruby 的 CSV 模块,我相信我只能通过索引访问字段。我认为上面的代码会更具可读性。有什么想法吗?
最佳答案
使用 Ruby 1.9 及更高版本,您可以获得一个可索引的对象:
CSV.foreach('my_file.csv', :headers => true) do |row|
puts row['foo'] # prints 1 the 1st time, "blah" 2nd time, etc
puts row['bar'] # prints 2 the first time, 7 the 2nd time, etc
end
这不是点语法,但它比数字索引更好用。
顺便说一句,对于 Ruby 1.8.x FasterCSV是您使用上述语法所需要的。
关于ruby - 解析包含标题字段作为每行属性的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3717464/