How to put file elements in a hash? -Ruby

So, I have a file in the form:

Key1   Value1
Key2   Value2
Key3   Value3

separated by tab. My question is: how to open this file and put it in a hash? I 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 contains only the most recent entry ... I seem to want it all .....

+3
source share
2 answers

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

If you execute hash = foo, you reassign the 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
+8
source

Apply the answer from fooobar.com/questions/648986 / ... :

hash = Hash[*File.read(file_path).split("\t")]

It expands to

hash = Hash["Key1", "Value1", "Key2", "Value2", "Key3", "Value3"].

"\t" /\s+/ ( ).

0

Source: https://habr.com/ru/post/1714924/


All Articles