Search code examples
rubycsvblank-line

Read a blank column in a CSV file with Ruby


One line of the CSV is:

550012207,1,,,Y,,,,,Y,,

I'm doing:

product_id_a = data_values[0]
quantity_a = data_values[1]
product_id_b = data_values[5]

Each line is a scenario to put an order through, and some scenarios call for two products to be added to a cart. My problem is when there is only one item and column 5 is left blank.

I originally wrote:

if product_id_b == '' || ' '
   do nothing
else
  code to navigate to second product
end

I used '' || ' ' to try either one because when I tried them separately it ignores the if and does the else. I then wrote this just to double check:

if product_id_b == ' '
    puts '1'
  elsif product_id_b == ''
    puts '2'
  elsif product_id_b != '' || ' '
    puts 'nothing'
  end

And it puts "nothing", so I have no idea what the value is. When I do:

  puts product_id_a
  puts product_id_b
  puts quantity_a 

It outputs

 550012207, , 1

How do I identify this unknown value?


Solution

  • If you've used CSV.parse for parsing (I hope you do), you could mention that empty fields will be parsed as nils:

    CSV.parse('550012207,1,,,Y,,,,,Y,,')
    # => [["550012207", "1", nil, nil, "Y", nil, nil, nil, nil, "Y", nil, nil]]
    

    Solution: ActiveSupport library (and Rails) gives us very handy method: .blank?, you may use it to test if some value is blank: empty, consists only from spaces or nil.

    ''.blank? # => true
    '    '.blank? # => true
    nil.blank? # => true
    5.blank?   # => false