Arrays Ruby:NoMethodError在比较数组中的元素时
我正在研究一种方法,该方法将一个单词数组作为参数,并返回一个数组数组,其中每个子数组包含的单词是彼此的字谜。当sort_array[i][1]==temp do为nil:NilClass(NoMethodError)抛出Arrays Ruby:NoMethodError在比较数组中的元素时,arrays,ruby,nomethoderror,Arrays,Ruby,Nomethoderror,我正在研究一种方法,该方法将一个单词数组作为参数,并返回一个数组数组,其中每个子数组包含的单词是彼此的字谜。当sort_array[i][1]==temp do为nil:NilClass(NoMethodError)抛出未定义的方法“[]”时,行,我不知道为什么 def combine_anagrams(words) sort_array = Hash.new words.each do |w| sort_array[w] = w.split("").sort end sort_ar
未定义的方法“[]”时,行,我不知道为什么
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'] )
def组合字符(单词)
sort_array=Hash.new
单词。每个单词都有|
排序_数组[w]=w.split(“”)。排序
结束
sort_array=sort_array.sort_by{w,s | s}
返回数组=[]
i=0
而i看起来这是因为您正在递增i
变量,而没有检查以确保仍然在排序数组的范围内。要查看问题,请在代码中最内部的while
循环中放入puts
语句:
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
在你的代码中插入一些日志记录,你就会明白为什么。不知道答案这么简单!非常感谢。
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"]]