Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby 1.9 CSV: selectively ignoring conversions for a column
    text
    copied!<p>I have following CSV data:</p> <pre><code>10,11,12.34 </code></pre> <p>I can parse this using CSV from the standard library, and have the values converted from strings to numbers:</p> <pre><code>require 'csv' CSV.parse( "10,11,12.34" ) =&gt; [["10", "11", "12.34"]] CSV.parse( "10,11,12.34", {:converters =&gt; [:integer,:integer,:float]} ) =&gt; [[10, 11, 12.34]] </code></pre> <p>I <em>don't</em> want to convert column 1, I'd just like that left as a string. My guess was I could omit a value from the converters array, but that didn't work:</p> <pre><code>CSV.parse( "10,11,12.34", {:converters =&gt; [nil,:integer,:float]} ) NoMethodError: undefined method `arity' for nil:NilClass from /home/ian/.rvm/rubies/jruby-1.6.6/lib/ruby/1.9/csv.rb:2188:in `convert_fields' from org/jruby/RubyArray.java:1614:in `each' from /home/ian/.rvm/rubies/jruby-1.6.6/lib/ruby/1.9/csv.rb:2187:in `convert_fields' from org/jruby/RubyArray.java:2332:in `collect' from org/jruby/RubyEnumerator.java:190:in `each' from org/jruby/RubyEnumerator.java:404:in `with_index' from /home/ian/.rvm/rubies/jruby-1.6.6/lib/ruby/1.9/csv.rb:2186:in `convert_fields' from /home/ian/.rvm/rubies/jruby-1.6.6/lib/ruby/1.9/csv.rb:1923:in `shift' from org/jruby/RubyKernel.java:1408:in `loop' from /home/ian/.rvm/rubies/jruby-1.6.6/lib/ruby/1.9/csv.rb:1825:in `shift' from /home/ian/.rvm/rubies/jruby-1.6.6/lib/ruby/1.9/csv.rb:1767:in `each' from org/jruby/RubyEnumerable.java:391:in `to_a' from /home/ian/.rvm/rubies/jruby-1.6.6/lib/ruby/1.9/csv.rb:1778:in `read' from /home/ian/.rvm/rubies/jruby-1.6.6/lib/ruby/1.9/csv.rb:1365:in `parse' from (irb):25:in `evaluate' </code></pre> <p>In fact I haven't been able to find any way of specifying that I'd like the first column to be left unconverted. Any suggestions?</p> <hr> <p><strong>Update</strong></p> <p>I think I misunderstood the design intention for <code>:converters</code>. It's not a 1:1 mapping by column, but a list of converters to be applied (I think) to all values. I'm not sure, the docs aren't too clear. So the more general question is: How do I convert some columns in my CSV, and not others?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload