标题真的没有说明什么。我的情况是我想读取一个文件并将内容放入哈希中。现在,我想让它更聪明,我想创建一个循环来打开目录中的每个文件并将其放入哈希中。问题是我不知道如何分配一个相对于文件名的名称。例如:
hash={}
Dir.glob(path + "*") do |datafile|
file = File.open(datafile)
file.each do |line|
key, value = line.chomp("\t")
# Problem here is that I wish to have a different
# hash name for every file I loop through
hash[key]=value
end
file.close
end
这可能吗?
最佳答案
为什么不使用一个散列,它的键是文件名(在你的例子中是“数据文件”),它的值是你插入数据的散列?
hash = Hash.new { |h, key| h[key] = Hash.new }
Dir.glob(path + '*') do |datafile|
next unless File.stat(datafile).file?
File.open(datafile) do |file|
file.each do |line|
key, value = line.split("\t")
puts key, value
# Different hash name for every file is now hash[datafile]
hash[datafile][key]=value
end
end
end
关于ruby - 当它已经分配给某些东西时,你如何分配新的变量名? ruby ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1358359/