Module: CSVHash
Constant Summary collapse
- VERSION =
"0.1.3"
Instance Method Summary collapse
Instance Method Details
#from_file(file) ⇒ Object
6 7 8 9 10 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 37 38 39 40 41 42 43 |
# File 'lib/csv-hash.rb', line 6 def from_file file num = 0 data = [] columns = [] CSV.foreach(file) do |row| num += 1 if num == 1 columns = row.collect {|c| c.strip if c} next end hash = {} columns.each_with_index do |col, i| next unless col col = col ? col.strip : nil val = row[i] ? row[i].strip : nil setter = hash sp = col.split('__') sp.each_with_index do |key, j| if j == sp.size - 1 setter[key] = val else setter[key] ||= {} setter = setter[key] end end end data << hash end return data, columns.compact end |
#to_string(hashes, columns) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/csv-hash.rb', line 45 def to_string hashes, columns rows = hashes.collect do |hash| vals = columns.collect do |col| sp = col.to_s.split('__') ret = hash sp.each do |key| puts key unless ret ret = ret[key] end ret end vals end csv_string = CSV.generate do |csv| csv << columns rows.each do |val| csv << val end end end |