我正在研究一种方法,该方法将一个单词数组作为参数并返回一个数组数组,其中每个子数组包含的字是彼此的字谜。第while sort_array[i][1]==temp do
行投掷undefined method '[]' for nil:NilClass (NoMethodError)
,我不明白为什么。
def combine_anagrams(words)
sort_array = Hash.new
words.each do |w|
sort_array[w] = w.split("").sort
end
sort_array = sort_array.sort_by { |w, s| s }
return_array = []
i = 0
while i<sort_array.length do
temp_array = []
temp = sort_array[i][1]
while sort_array[i][1]==temp do
temp_array += [sort_array[i][0]]
i+=1
end
return_array += [temp_array]
end
return temp_array
end
p combine_anagrams( ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams','scream'] )
答案 0 :(得分:1)
看起来这是因为您正在增加i
变量而不检查以确保您仍然在sort_array
的范围内。要查看问题,请在代码中最内部puts
循环中添加while
语句:
while sort_array[i][1]==temp do
temp_array += [sort_array[i][0]]
i+=1
puts "i is #{i} and the length is #{sort_array.length}"
end
然后运行您的代码,您将看到:
i is 1 and the length is 8
i is 2 and the length is 8
i is 3 and the length is 8
i is 4 and the length is 8
i is 5 and the length is 8
i is 6 and the length is 8
i is 7 and the length is 8
i is 8 and the length is 8
example.rb:15:in `combine_anagrams': undefined method `[]' for nil:NilClass (NoMethodError)
您需要确保在两个while循环中保持在数组的范围内,例如:
while i < sort_array.length && sort_array[i][1]==temp do
end
作为旁注,您的代码目前仅返回上一个temp_array
,因为您还在外部while
循环的开头重置了该代码。而且,如果我了解您尝试解决的问题,可能需要查看阵列上的group_by
,这要归功于Enumerable模块:
words = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams','scream']
words.group_by { |word| word.chars.sort }.values
# => [["cars", "racs", "scar"], ["for"], ["potatoes"], ["four"], ["creams", "scream"]]