ruby / csv

CSV Reading and Writing
https://ruby.github.io/csv/
BSD 2-Clause "Simplified" License
182 stars 114 forks source link

`require 'csv'; CSV.generate { |csv| csv << {a: 1, b: 2} }` throws `undefined method 'collect' for nil` #314

Open dorianmariecom opened 3 months ago

dorianmariecom commented 3 months ago

What's weird is that it works with structs (and arrays of course) but not with hashes

>> require 'csv'; CSV.generate { |csv| csv << {a: 1, b: 2} }
/Users/dorianmariefr/.asdf/installs/ruby/3.3.4/lib/ruby/gems/3.3.0/gems/csv-3.3.0/lib/csv/writer.rb:36:in `<<': undefined method `collect' for nil (NoMethodError)

        row = @headers.collect {|header| row[header]}
                      ^^^^^^^^
    from /Users/dorianmariefr/.asdf/installs/ruby/3.3.4/lib/ruby/gems/3.3.0/gems/csv-3.3.0/lib/csv.rb:2373:in `<<'
    from (irb):2:in `block in <top (required)>'
    from /Users/dorianmariefr/.asdf/installs/ruby/3.3.4/lib/ruby/gems/3.3.0/gems/csv-3.3.0/lib/csv.rb:1410:in `generate'
    from (irb):2:in `<main>'
    from <internal:kernel>:187:in `loop'
    from /Users/dorianmariefr/.asdf/installs/ruby/3.3.4/lib/ruby/gems/3.3.0/gems/irb-1.14.0/exe/irb:9:in `<top (required)>'
    from /Users/dorianmariefr/.asdf/installs/ruby/3.3.4/bin/irb:25:in `load'
    from /Users/dorianmariefr/.asdf/installs/ruby/3.3.4/bin/irb:25:in `<main>'
kou commented 3 months ago

You need to specify headers:: CSV.generate(headers: [:a, :b]) {|csv| csv << {a: 1, b: 2}}