Skip to content

Instantly share code, notes, and snippets.

@rondale-sc
Created November 30, 2011 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondale-sc/1409526 to your computer and use it in GitHub Desktop.
Save rondale-sc/1409526 to your computer and use it in GitHub Desktop.
Create hash from CSV using first field as key for a field hash based on header row
# encoding: utf-8
require 'csv'
require 'pp'
class CodeSearch
def initialize(csv)
@file_path = csv
parse
end
def [](index)
@values[index]
end
def parse
@values = Hash.new {|k,v| k[v] = Hash.new}
line_array = CSV.read(@file_path)
header = line_array.shift
line_array.each do |row|
tmp_hash = {}
header.each_with_index do |v,i|
tmp_hash[v.downcase.gsub(' ', '_').to_sym] = row[i]
end
@values[row.shift] = tmp_hash
end
@values
end
end
c = CodeSearch.new('/path/to/csv')
pp c[:first_item_of_row_key]
#=> { "first_item_of_row_key" => "first_item_of_row_value",
# "second_item_of_row_key" => "second_item_of_row_value" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment