tags:

views:

293

answers:

1

So I have a file in the form of:

Key1   Value1
Key2   Value2
Key3   Value3

seperated by a tab. My question is how do I open this file and put it into a hash? I have tried to do:

 fp = File.open(file_path)

 fp.each do |line|
   value = line.chomp.split("\t")
   hash = Hash[*value.flatten]
 end

But at the end of this loop the @datafile hash only contains the latest entry...I kinda want it all.....

+4  A: 

hash[key] = value to add a new key-value pair. hash.update(otherhash) to add the key-value-pairs from otherhash to hash.

If you do hash = foo, you reassign hash, losing the old contents.

So for your case, you can do:

hash = {}
File.open(file_path) do |fp|
  fp.each do |line|
    key, value = line.chomp.split("\t")
    hash[key] = value
  end
end
sepp2k
Don't forget to instantiate hash (hash = {}) before the File.open block, or else it won't be available following the last end statement.
glenn jackman
Good point. Fixed.
sepp2k