Created
November 30, 2011 15:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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