Module: FruitToLime::CsvHelper

Defined in:
lib/fruit_to_lime/csv_helper.rb

Class Method Summary collapse

Class Method Details

.text_to_hashes(text, column_separator = nil, row_separator = :auto, quote_char = '"') ⇒ Object

Examples:

Detect column separator and transform to hashes

hashes = FruitToLime::CsvHelper.text_to_hashes(text)

Use specific column separator and transform to hashes

column_separator = ','
hashes = FruitToLime::CsvHelper.text_to_hashes(text, column_separator)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/fruit_to_lime/csv_helper.rb', line 11

def self.text_to_hashes(text, column_separator = nil, row_separator = :auto, quote_char = '"')
    if !text
        raise "Missing text"
    end

    if !column_separator
        column_separator = self.detect_col_sep text
    end

    rows = CSV.parse(text.strip,{:col_sep => column_separator, 
        :row_sep => row_separator, :quote_char => quote_char})
    map = {}
    first = rows.first 
    (0 .. first.length-1).each do |i|
        map[i] = first[i]
    end
    rs = []
    (1 .. rows.length-1).each do |i|
        r={}
        (0 .. map.length-1).each do |j|
            r[map[j]] = rows[i][j]
        end
        rs.push(r)
    end
    return rs
end