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 < nums.length idx2 = idx1 + 1 while idx2 < 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.
-1, -2, 2, 1which pair is first? \$\endgroup\$