module CSVHash
Constants
- VERSION
Public Instance Methods
from_file(file)
click to toggle source
# 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)
click to toggle source
# 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