Find indices of first pair of numbers that sums to zero Here is the task from a beginner's course: 


  Write a method that takes an array of numbers. If a pair of numbers in the array sums to zero, return the positions of those two numbers. If no pair of numbers sums to zero, return nil.


This model solution does not use idiomatic Ruby, because at that point in the course, we had only learned traditional loops. I'm trying to go back now and understand how to use idiomatic Ruby to accomplish the same tasks.

Model solution:


def two_sum(nums)

idx1 = 0

while idx1 &lt; nums.length

idx2 = idx1 + 1

while idx2 &lt; nums.length

  if nums[idx1] + nums[idx2] == 0

    return [idx1, idx2]

  end


  idx2 += 1

end


idx1 += 1

end


return nil

end



My solution:

def two_sum(nums)

answer = []

nums.each_with_index do |num1, idx1|
    nums.each_with_index {|num2, idx2| answer.push(idx1, idx2) if (num1 + num2) == 0 }  
end

    answer.empty? ? nil : answer[0..1]

end


The call of only the first two items in the answer array seems cheap. There must be a better way. I'm just not sure how to work through the array including the index, but also breaking as soon as the array hits a length of two, or however else one might define it.
The problem can be solved in less than quadratic time. Sort the elements by absolute value, then search for consecutive elements that sum up to zero.

def two_sum(nums)
    temp = nums.map.with_index { |x, i| [x, i] }
    temp.sort_by! { |x| x[0].abs }
    for x in temp.zip(temp.rotate)
        if x[0][0] + x[1][0] == 0
            return [x[0][1], x[1][1]]
        end
    end
    return nil
end