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.....
Apply an answer from https://stackoverflow.com/a/4120285/2097284:
hash = Hash[*File.read(file_path).split("\t")]
This expands to
hash = Hash["Key1", "Value1", "Key2", "Value2", "Key3", "Value3"]
.For more robustness, replace
"\t"
with/\s+/
(to allow any kind of whitespace).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: