2017-02-10 99 views
-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"] 
+0

没有按什么方面呢不工作? – splrs

+0

@splrs我不知道如何添加一个数组到一个散列键,因为这一个替换值s.t. “伦敦”只有最后的价值,在这种情况下,它是“巴黎” –

回答

0
File.open(file).each_line.drop(1) 
.map(&:split) 
.group_by(&:first) 
.map{|k, v| [k, v.map(&:last).uniq]} 
# => [ 
    ["London", ["Paris", "NYC"]], 
    ["NYC", ["Cairo"]], 
    ["Cairo", ["Rome"]] 
] 

在Ruby 2.4中:

File.open(file).each_line.drop(1) 
.map(&:split) 
.group_by(&:first) 
.transform_values{|v| v.map(&:last).uniq} 
# => { 
    "London" => ["Paris", "NYC"], 
    "NYC" => ["Cairo"], 
    "Cairo" => ["Rome"] 
} 
0

回答您的问题更新:

现在的问题是如何添加独特的价值?

您可以使用none?,像这样:

h[from].push(to) if h[from].none? { |i| i == to } 

也可以考虑使用一组(只包含独特元素),而不是数组:

require 'set' 

set = Set.new ['a','b'] 
#=> #<Set: {"a", "b"}> 
set << 'a' 
#=> #<Set: {"a", "b"}>