-1
我有.txt文件下列输入:哈希具有多个值
FROM TO
London Paris
London NYC
NYC Cairo
Cairo Rome
London Paris
,我需要让所有的唯一目的地的TO
"London" -> ["Paris", "NYC"]
"NYC" -> ["Cairo]
"Cairo" -> ["Rome"]
,这样我可以用另一个数组对它们进行比较看起来像这样的字符串A = [“维也纳”,“卢森堡”,“罗马”]。
此解决方案不起作用。
h = Hash.new{|hash, key| hash[key]}
lineCounter = 0
file = File.open(arcFile2,"r")
Line = file.first.split(" ")
file.each_line do |line|
if lineCounter == 0 then
lineCounter = lineCounter + 1
elsif lineCounter > 0 then
Line = line.split("\t")
from = Line[firstLine.index "from"].to_s.chomp
to = Line[firstLine.index "to"].to_s.chomp
h[from] = to
end
end
puts h["London"] & A
编辑:代码工作时,我定义我的哈希值如下:
h = Hash.new{|hash, key| hash[key] = Array.new}
h[from].push to
现在的问题是我如何,因为在这种情况下,添加独特的价值观,我将有
"London" -> ["Paris", "NYC", "Paris"]
没有按什么方面呢不工作? – splrs
@splrs我不知道如何添加一个数组到一个散列键,因为这一个替换值s.t. “伦敦”只有最后的价值,在这种情况下,它是“巴黎” –