使用Ruby中的标题过滤到新的CSV?

时间:2017-02-17 01:43:58

标签: ruby csv header

我有一张CSV,其中包含人员,性别和年龄的基本列表以及相应的标题:

"First Name","Age","Gender"
"Adam",31,"Male"
"Bruce",36,"Male"
"Lawrence",34,"Male"
"James",32,"Male"
"Elyse",30,"Female"
"Matt",32,"Male"

我想在Ruby中打开此CSV,逐行浏览,并将所有男性成员附加到具有相同标题的新CSV,并将此CSV保存到新文件中。

我的代码现在(不起作用)

require 'csv'

file = 'cast.csv'

new_cast = CSV.new(:headers => CSV.read(file, :headers => :true).headers)

CSV.foreach(file, :headers => :true, :header_converters => :symbol) do |row|
    if row[:gender] == 'Male'
        new_cast.add_row(row)
    end
end

File.open('new_cast.csv', 'w') do |f|
  f.write(new_cast)
end

我收到的错误讯息:

/usr/local/Cellar/ruby/2.3.0/lib/ruby/2.3.0/csv.rb:1692:in `<<': undefined method `<<' for {:headers=>["First Name", "Age", "Gender"]}:Hash (NoMethodError)
Did you mean?  <
    from csv.rb:8:in `block in <main>'
    from /usr/local/Cellar/ruby/2.3.0/lib/ruby/2.3.0/csv.rb:1748:in `each'
    from /usr/local/Cellar/ruby/2.3.0/lib/ruby/2.3.0/csv.rb:1131:in `block in foreach'
    from /usr/local/Cellar/ruby/2.3.0/lib/ruby/2.3.0/csv.rb:1282:in `open'
    from /usr/local/Cellar/ruby/2.3.0/lib/ruby/2.3.0/csv.rb:1130:in `foreach'
    from csv.rb:6:in `<main>'

所以,看起来我做错了。最简单的方法是什么?

1 个答案:

答案 0 :(得分:0)

CSV#new采用&#34;字符串或IO对象&#34;作为第一个参数,第二个是per the docs

所以看起来错误实际上是由这一行引起的:

new_cast = CSV.new(:headers => CSV.read(file, :headers => :true).headers)

应该是

new_cast = CSV.new("", :headers => CSV.read(file, :headers => :true).headers)

请注意空字符串。

但即便如此,这也不会写新的CSV。为此,我认为您希望在新CSV中write_headers,然后在撰写之前rewind展示基础IO object

require 'csv'

file = 'cast.csv'

new_cast = CSV.new("", :headers => CSV.read(file, :headers => :true).headers, write_headers: true)

CSV.foreach(file, :headers => :true, :header_converters => :symbol) do |row|
  if row[:gender] == 'Male'
    new_cast.add_row(row)
  end
end

CSV.open('new_cast.csv', 'w') do |csv|
  new_cast.rewind
  new_cast.each {|row| csv << row}
end

希望有所帮助!