Jack Kelly Jack Kelly - 1 month ago 6
Ruby Question

I want to understand this "duplicates?" method

I can't seem to wrap my head around this method. If I would try to comprehend this code I would say that the items are iterated over and indexed twice so that there are two seperate iterations of the array. If both collections of indexes are the same return true if both collections of items are the same.

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


Obviously i'm mistaken otherwise the method would always return true. How am i mistaken?

Answer

The algorithm is

for each element in array
  for each element in array
    skip if indices match
    return true if elements are the same 

return false

Pretty simple really.

Comments