Clean up my two_sums with indices

I’m just wondering if there is a cleaner way to write this, without
having to use 2 each.with_index’s: I need to find if 2 numbers within an
array sum to zero, and if they do return the indices of said numbers.

def two_sum(nums)
nums[0…-2].each.with_index do |num1,idx1|
nums[idx1+1…-1].each.with_index do |num2,idx2|
return [idx1, idx1+idx2+1] if num1 + num2 == 0
end
end
nil
end

It just looks ugly. Thanks - Jay

Jason G. wrote in post #1167664:

I’m just wondering if there is a cleaner way to write this, without
having to use 2 each.with_index’s: I need to find if 2 numbers within an
array sum to zero, and if they do return the indices of said numbers.

It just looks ugly. Thanks - Jay

def two_sum2(nums)
nums.permutation(2).each { |(a,b)|
return [nums.index(a),nums.index(b)] if a+b==0
}
nil
end

l=(1…1000).map { rand(-10000…+10000) }
p two_sum2(l)

def two_sum2(nums)
nums.permutation(2).each { |(a,b)|
return [nums.index(a),nums.index(b)] if a+b==0
}
nil
end

l=(1…1000).map { rand(-10000…+10000) }
p two_sum2(l)

Thanks! I didn’t know about permutation. Just read about it on Ruby-doc.