Sagar RS Sagar RS - 4 years ago 115
Ruby Question

How to remove the delimiters from a csv file in ruby

I am reading a file which is either separated by a "tab space" or "semicolon(;)" or "comma(,)" below code separates only tab space but i want all 3 to be checked. like if a file is comma separated it should work for that also . Please help!

#!/usr/bin/ruby

require 'csv'

test = CSV.read('test.csv', headers:true, :col_sep => "\t")
x = test.headers
puts x

Answer Source

It looks like :col_sep cannot be a Regexp, which could have solved your problem.

One possible solution would be to analyze the head of your CSV file and count the occurences of possible separators :

require 'csv'

possible_separators = ["\t", ';', ',']
lines_to_analyze = 1

File.open('test.csv') do |csv|
  head = csv.first(lines_to_analyze).join
  @col_sep = possible_separators.max_by { |sep| head.count(sep) }
end

@col_sep
#=> ";"

You can then use :

test = CSV.read('test.csv', headers:true, :col_sep => @col_sep) 
x = test.headers
puts x
# a
# b
# c

The values in x won't contain any separator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download