I want to determine which separator is used in a csv file. CSV.foreach will return something like this:
["something1;something2;something3"]
The code beneath does the trick, but something better must exist. I find it annoying to have the need for sep_count. Do you know of a method that returns the most frequent of the characters from SEPERATORS?
SEPERATORS = [";", ","]
CSV.foreach(@file, @config) do |header|
sep_count = 0
SEPERATORS.each do |seperator|
if header.first.scan(/#{seperator}/).count > sep_count
@config[:col_sep] = seperator
sep_count = header.first.scan(/#{seperator}/).count
end
end
break
end
EDIT:
Based on your awesome answers I got the 1-liner that I asked for:
@config[:col_sep] = %w(; ,).sort_by { |separator| File.open(@file).first(1).join.count(separator) }.last
I have also come up with this piece of code that determines both col_sep and row_sep:
first_line = ""
File.open(@file) do |file|
file.each_char do |char|
first_line << char
if "\r\n".include?(char)
@config[:row_sep] = first_line.scan(/\n$|\r$/).first
break
end
end
end
@config[:col_sep] = %w(; ,).sort_by { |separator| first_line.count(separator) }.last
By using the full code we ensure that it is always the first line that gets used, and we also set the row_sep. Feel free to comment if you think anything could be improved further.