Question : csv to hash - ruby

Hello
How can I now retrieve certain keys and there values from the hash - tried, but keep getting an error
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
require 'csv' 
file = "C:/Documents and Settings/p.sivyer/RUBY/RUBY_WORKING_MODELS/csv_master.txt" 
rows = CSV::Reader.parse(File.open(file)).to_a
cols = rows.shift
collection = rows.collect do |row|  
Hash[*cols.zip(row).flatten]
end 
puts collection.first.inspect
Open in New Window Select All

Answer : csv to hash - ruby

There are a few different options, depending on exactly what you want.  (I'll assume "Col1" and "Col3" are names of keys you want below.)

If you know the keys that you want, you obviously can just use them.  (See first example below.)

However, the best general solution is probably just using 'each' (which is synonymous with 'each_pair' with a Hash).  Note the use of two variables in the block.

(Or did I miss the point again?)
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
# just using the keys
puts "Col1: #{collection.first["Col1"]}\tCol3: #{collection.first["Col3"]}"
 
# using 'each' to output each and every hash value
collection.each {|row|  # each row is a hash
  row.each {|key, value|
    if key == 'col1' or key == 'Col3'
      puts "#{key}: #{value}"
    end
  }
  puts "-----"
}
Open in New Window Select All
Random Solutions  
 
programming4us programming4us