Ruby的CSV类可以很容易地迭代每一行:
CSV.foreach(file) { |row| puts row }
但是,这总是包含标题行,所以我将得到输出:
header1, header2
foo, bar
baz, yak
我不想要标题.现在,当我打电话给...
CSV.foreach(file, :headers => true)
我得到这个结果:
#<CSV::Row:0x10112e510
    @header_row = false,
    attr_reader :row = [
        [0] [
            [0] "header1",
            [1] "foo"
        ],
        [1] [
            [0] "header2",
            [1] "bar"
        ]
    ]
>
当然,因为文档说:
此设置使#shift将行返回为CSV :: Row对象而不是Arrays
但是,如何跳过标题行,将行作为简单数组返回?我不希望CSV::Row返回复杂的对象.
我绝对不想这样做:
first = true
CSV.foreach(file) do |row|
  if first
    puts row
    first = false
  else
    # code for other rows
  end
end
wal*_*.ar 15
从CSV类看#shift:
包装字符串和IO的主要读取方法,从数据源中提取单行,解析并作为字段数组返回(如果未使用标题行)
一个例子:
require 'csv'
# CSV FILE
# name, surname, location
# Mark, Needham, Sydney
# David, Smith, London
def parse_csv_file_for_names(path_to_csv)
  names = []  
  csv_contents = CSV.read(path_to_csv)
  csv_contents.shift
  csv_contents.each do |row|
    names << row[0]
  end
  return names
end
忽略标题的一种很酷的方法是将其作为数组读取并忽略第一行:
data = CSV.read("dataset.csv")[1 .. -1]
# => [["first_row", "with data"],
      ["second_row", "and more data"],
      ...
      ["last_row", "finally"]]
该:headers => false方法的问题在于CSV不会尝试将第一行作为标题读取,而是将其视为数据的一部分.所以,基本上,你有一个无用的第一行.