Module: Array::ToCSV

Included in:
Array, Enumerable
Defined in:
lib/epitools/core_ext/array.rb

Instance Method Summary collapse

Instance Method Details

#to_csv(delimiter = ",") ⇒ Object

Convert this enumerable into a CSV string (nb: enumerable must contain either all Hashes or all Arrays)



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/epitools/core_ext/array.rb', line 331

def to_csv(delimiter=",")
  types = count_by(&:class)

  unless types.size == 1 and (types[Array] > 0 or types[Hash] > 0)
    raise "Error: this array must contain nothing but arrays, or nothing but hashes (actually contains: #{types.inspect})"
  end

  options = {}
  options[:col_sep] = delimiter
  options[:headers] = flat_map(&:keys).uniq if types[Hash] > 0

  CSV.generate(nil, **options) do |csv|
    each { |obj| csv << obj }
  end
end

#to_tsvObject

Like #to_csv, but with tab-separated CSV fields



350
351
352
# File 'lib/epitools/core_ext/array.rb', line 350

def to_tsv
  to_csv("\t")
end