Tuesday, June 24, 2008

Ruby -- How to turn a csv file into a list of has

There are convenience libraries for this type of thing, but I thought I would plunk down my solution.
Say you have a csv string and you need to just turn it into a proper Ruby data structure. A list of hashes would be nice since this is the same type of data structure you typically work with when you query a DBMS. Here is a function to do this.

def turn_csv_into_list_of_hashes(string)
  returned_list = []
  #the first line should be header
  rows = string.split("\n")
  header = rows.shift.split(',')
  rows.each do |row|
    row_hash = {}
    row.split(",").each_with_index { |item, i| row_hash[header[i]] = item }
    returned_list << row_hash
  end
  return returned_list
end

No comments: