如何将文件的元素放入散列? -红宝石 [英] How to put elements of a file into a hash? -Ruby

查看:93
本文介绍了如何将文件的元素放入散列? -红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个文件格式为:

  Key1 Value1 
Key2 Value2
Key3 Value3

由选项卡分隔。我的问题是我如何打开这个文件并将其放入哈希?我曾试图这样做:

  fp = File.open(file_path)

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

但是在循环结束时,@datafile散列只包含最新的条目......我有点想要它......

解决方案

hash [key] = value 添加一个新的键值对。 hash.update(otherhash)从otherhash添加键值对到哈希。



如果你这样做 hash = foo ,您可以重新分配散列值,丢失旧内容。

  hash = {} 
File.open(file_path)do | fp |
fp.each do | line |
key,value = line.chomp.split(\ t)
hash [key] = value
end
end


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

解决方案

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

这篇关于如何将文件的元素放入散列? -红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆