我有兩種方法:Ruby中的遞歸問題:我是否遇到副作用?
def word_square_word_list
@word_list.each do |word|
return_value = find_next_word([word])
#check return_value here and it is completely different than what is returned from the find_next_word method.
return return_value if is_list_valid?(return_value)
end
end
def find_next_word(word_list_array)
if word_list_array.length == @size_of_square
#confirm word_list_array is what I expect here
word_list_array
else
start_of_next_word = word_list_array.map{|w| w[word_list_array.length]}.join
get_all_words_that_start_with(start_of_next_word).each do |word|
find_next_word(word_list_array + [word])
end
end
end
我可以用binding.pry
確認由find_next_word
返回word_list_array
其實正確的值。但是當我去檢查返回值時,它是完全不同的東西。
我可以想出唯一的解釋是,我正在經歷實施的副作用。有沒有人有什麼想法可能會導致這一點?
如果'word_list_array.length == @ size_of_square'爲false,那麼'find_next_word'的返回值將是'get_all_words_that_start_with(start_of_next_word)'列表。遞歸在最終的返回值中丟失。 – Matt
@Matt,我通過pry證實,這不是虛假的,因爲我最終在裏面。但是,你解釋的是我正在經歷的症狀。儘管如此,我認爲這與Alex的解釋有關。 –