我有一个基本的红宝石问题。不久之前做了一些教程,但似乎无法解决这个问题:
class DependencyReader
@tree
@dependenciesFromFile
def read_file
@tree = { }
file = File.new("resources/2.Resource.txt", "r")
@dependenciesFromFile = Hash.new
while (line = file.gets)
splitLine = line.split
firstLetter = splitLine.shift
firstLetter.downcase!
depenendenciesInRow = splitLine
@dependenciesFromFile[firstLetter] = depenendenciesInRow
end
get_tree 'a'
file.close
end
def get_tree(letter)
unless @tree.has_key? letter
#add the index to that tree
@tree[letter] = Array.new
end
puts @tree
@tree.each do |key, value|
value.push(@dependenciesFromFile[letter])
end
puts @dependenciesFromFile
#prints
# {"a"=>["B", "C"], "b"=>["C"], "c"=>["D", "E"], "d"=>["F"]}
puts @dependenciesFromFile["a"]
#prints nothing
#gives error
@dependenciesFromFile["a"].each do |key, value|
get_tree value
end
puts @tree
end
end
问题出现在这里:
puts @dependenciesFromFile
#prints
# {"a"=>["B", "C"], "b"=>["C"], "c"=>["D", "E"], "d"=>["F"]}
puts @dependenciesFromFile["a"]
#prints nothing
#gives error
@dependenciesFromFile["a"].each do |key, value|
get_tree value
end
它当然已经填满了,但是当我尝试用字符串作为键来读它时。它没有任何回报。
之后,.each方法会出错,因为它无法循环Nil
编辑:
调用read_file方法的另一个类的代码,该方法调用get_tree方法。
reader = DependencyReader.new
reader.read_file
答案 0 :(得分:0)
在包含错误的代码段中,您不应该使用arguments passed
而不是"a"
,如下所示:
puts @dependenciesFromFile
#prints
# {"a"=>["B", "C"], "b"=>["C"], "c"=>["D", "E"], "d"=>["F"]}
puts @dependenciesFromFile[letter]
#should print a array
#should resolve error
@dependenciesFromFile[letter].each do |key, value|
get_tree value
end