I am currently learning ruby and am very new to it. I usually write code in javascript but because I am entering a bootcamp next year I took it upon myself to learn as much ruby before my cohort starts. So the practice problem that I'm trying to solve is getting the indices of elements that equivalent to a certain number, in which case lets give an example 0.
I can do this with no problem for JS but I am learning how to write in Ruby.
//JS
for(let i = 0; i < arr.length; i++){
for(let j = i + 1; j < arr.length; j++){
if(arr[j] + arr[i] === 0){
someVar.push([i,j]);
}
}
}
The block code above displays where I am getting each unique pair and which ever one of these pairs return a sum 0 their indices get pushed inside the result.
I am still very new with how ruby writes loops and there is a plethora of ways to do it.
def two_sum(nums)
result = []
n = nums.length
n.times do |i|
n.times do |j|
if nums[i] + nums[j] == 0
result.push([i,j])
end
end
end
result
end
I've tried doing it this way but it doesn't give me the right output. I also understand that n.times do |j|
is not the same as for(let j = i + 1; j < arr.length; j++)
. But I don't know how else to write this so I did something like:
n.times do |i|
x = i + 1
x.times do |j|
My intuition is telling me that this is not the way to write an inner loop.