How to put elements of a file into a hash? -Ruby

2019-04-11 07:58发布

问题:

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.....

回答1:

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


回答2:

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).



标签: ruby hash