Two_sum practice errors

I basically created the same code as the tutorial video in the alpha course, but i got error: (repl):17: syntax error, unexpected ‘,’, expecting ')'
two_sum ([1,2,4], 5)
_ ^_
I’m testing it in repl.it

def two_sum (arr, target)
while idx_1<arr.length
idx_1=0
while idx_2 < arr.length - 1
idx_2 = idx_1 + 1
while idx_2 < arr.length
if arr[idx_1]+arr[arr_2] == target
return true
else
idx_2+=1
end
end
idx_1+=1
end
return false
end
two_sum ([1,2,4], 5)

This code is hard to debug because the error message isn’t very useful. I recommend using indentations to check what might be wrong. Indenting your code gives you this:

def two_sum (arr, target)
  while idx_1<arr.length
    idx_1=0
      while idx_2 < arr.length - 1
        idx_2 = idx_1 + 1
          while idx_2 < arr.length
            if arr[idx_1]+arr[arr_2] == target
              return true
            else
              idx_2+=1
            end
        end
        idx_1+=1
      end
    return false
  end
two_sum ([1,2,4], 5)

You’ll notice that def two_sum (arr, target) isn’t on the same level as the final end, indicating that you’re missing an end before two_sum ([1,2,4], 5). Your code will run once you add an additional end. However, you will then get a new error. Let me know if you need help debugging this new error!

Thank you!
I was able to find the real error: instead of arr[idx_1]+arr[idx_2], I put arr[arr_2]. it runs fine after I fixed that.
I’ve always been very bad with indentations, do you just manually align them or is there an easier way to do it?

Sorry for the slow response!

I find that Atom is very helpful in suggesting the right indentation. For example, if I type def test and then hit enter, Atom will automatically indent the cursor on the next line. What editor are you using to write your code?

I’m using Atom for the task on alpha course, but i practice on repl.it so i can run and see the result…i dont think atom shows the result

Indenting properly is indeed not just there for cosmetic purposes-- as you just discovered, it plays an important role in debugging proper closures with end statements in Ruby.

It’s true that in repl.it the automatic indentation is not as nice as it is in Atom, but it still matters in both.

Note that the tab key indents, shift + tab un-indents, and you can do either operation with multiple lines selected.

You also should totally try running your own .rb files written in Atom in the terminal-- it’s best to get used to working in the terminal early. Just cd to the file in question, and then run it by typing ruby my_file.rb.

1 Like