Ruby 我想了解这一点;重复;方法
我似乎无法理解这种方法。如果我试图理解这段代码,我会说这些项被迭代并索引两次,这样数组就有两次独立的迭代。如果两个索引集合相同,则如果两个项集合相同,则返回trueRuby 我想了解这一点;重复;方法,ruby,algorithm,Ruby,Algorithm,我似乎无法理解这种方法。如果我试图理解这段代码,我会说这些项被迭代并索引两次,这样数组就有两次独立的迭代。如果两个索引集合相同,则如果两个项集合相同,则返回true def duplicates?(array1) array1.each_with_index do |item1, index1| array1.each_with_index do |item2, index2| next if index1 == index2 return true if i
def duplicates?(array1)
array1.each_with_index do |item1, index1|
array1.each_with_index do |item2, index2|
next if index1 == index2
return true if item1 == item2
end
end
false
end
显然我错了,否则该方法将始终返回true。我怎么弄错了?算法是错误的
for each element in array
for each element in array
skip if indices match
return true if elements are the same
return false
非常简单。我对ruby一无所知,但我认为它是这样的:对于每个元素,检查彼此是否相等。如果有:返回True;这意味着存在重复(停止算法;它只是二进制检查,可以通过函数名中的?识别)。其他:继续。如果所有检查都通过,则返回false=no dupes.Ahh。因此,如果索引匹配,则下一步If index==index2将跳过匹配的元素,如果数组中的某个项匹配,则返回true。现在,这是完全有道理的。非常感谢。