1

这有效:

    require 'csv'
    file = CSV.open(filename)
    puts file.shift

这不会:

    require 'csv'
    file = CSV.open(filename, :headers=>true)
    puts file.shift

我得到:

C:/Program Files (x86)/IronRuby 1.1/Lib/ruby/1.9.1/csv.rb:2177:in `convert_field
s': undefined method `with_index' for IronRuby.Builtins.Enumerator:Enumerator (N
oMethodError)
    from C:/Program Files (x86)/IronRuby 1.1/Lib/ruby/1.9.1/csv.rb:2218:in `
parse_headers'
    from C:/Program Files (x86)/IronRuby 1.1/Lib/ruby/1.9.1/csv.rb:1918:in `
shift'
    from C:/Program Files (x86)/IronRuby 1.1/Lib/ruby/1.9.1/csv.rb:1818:in `
loop'
    from C:/Program Files (x86)/IronRuby 1.1/Lib/ruby/1.9.1/csv.rb:1818:in `
shift'
    from C:/myproject/myproject/myproject/Program.rb:3

我正在使用 Ironruby 1.1.3

我正在寻找正确的语法来获得带有 headers 选项的单行。

4

2 回答 2

2

我在不同的引擎中对此进行了测试,这似乎是 Ironruby 中的一个错误

于 2012-06-07T08:15:01.803 回答
0

您可以试试这个,注意 colsep,使其适应 CSV 文件中的内容。如果要显示标题:

require 'csv'

path = "G:/documents/musicinfo"
Dir.glob("#{path}/**/*.csv").each {|file|
  CSV.foreach(file, :col_sep => ';') do |row|
    puts "#{file} => #{row}"
    break
  end
}

给出数组:

G:/documents/musicinfo/album.csv => ["album_release_year", "album_id", "artist_id", "album"]
G:/documents/musicinfo/artist.csv => ["artist_id", "artist_name"]
G:/documents/musicinfo/Copy of all2.csv => ["album_release_year,album_id,track_id,artist_id,artist_name,duration,genre,track_popularity,disc_number,track_number,track,album"]
G:/documents/musicinfo/genres.csv => ["genreId", " genreNaam"]
G:/documents/musicinfo/songs.csv => ["album_id", " track_id", " artist_id", " track_popularity", "genre_id", "track"]

而且,如果您想显示第一个数据行或将其保留为 CSV,请使用以下内容调整:

CSV.foreach(file, :col_sep => ';', :headers => true) do |row|

这使:

G:/documents/musicinfo/album.csv => 0000,10747312,11522976,Beyond Imagination (Bonus Track Version)
G:/documents/musicinfo/artist.csv => 10000004,Jimi Hendrix
G:/documents/musicinfo/Copy of all2.csv => "2008,12877382,24516577,10000004,Jimi Hendrix,05:39,Pop,9,16,1,10,Free spirit"
G:/documents/musicinfo/genres.csv => 1,Alternative
G:/documents/musicinfo/songs.csv => 12877382,24516577,10000004,9,16,Free spirit
于 2012-06-04T14:17:35.600 回答