Ad
  • Custom User Avatar

    Well, that's after I changed this:

        begin
          s1, s2 = two_sum(arr.dup, target)
        rescue NameError
          s1, s2 = twoSum(arr.dup, target)
        end
    

    For this:

        if defined?(two_sum)
          s1, s2 = two_sum(arr.dup, target)
        else
          s1, s2 = twoSum(arr.dup, target)
        end 
    

    Any idea why the first one gave that error instead of the out of bounds? I mean, hiding the real problem.

  • Default User Avatar
    main.rb:14:in `block (2 levels) in two_sum': undefined method `+' for nil:NilClass (NoMethodError)
    	from main.rb:12:in `loop'
    	from main.rb:12:in `block in two_sum'
    	from main.rb:11:in `loop'
    	from main.rb:11:in `two_sum'
    

    As it says, one of the arguments of the + inside the inner loop is nil, which means the index is out of bounds.

  • Custom User Avatar

    I saw it, but still I have no idea why that happens, sorry. Maybe someone who's more fluent in Ruby could find out why.

  • Custom User Avatar

    I'm gonna explain why that happens (I hope), but that part of the code should run only if your function isn't called two_sum.

        begin
          s1, s2 = two_sum(arr.dup, target)
        rescue NameError
          s1, s2 = twoSum(arr.dup, target)
        end
    

    And it's there for compatibility reasons. The Ruby translation used camelCase instead of snake_case at first and then that was changed. No idea why it would pass some tests and fail randomly. It doesn't happen with my solution.

  • Default User Avatar

    It's not that test you are failing but the previous one. Print the input at the beginning of your code.