Learning Ruby and trying out problems on Coderbyte. This code is supposed to find the number of numbers between numbers in an array. So [4,8,6] should return 2 (it needs 5 and 7 to be consecutive). [5,10,15] should return 8 and [-2,10,4] should return 10.
My solution is to get the difference between a number and its next greatest number, minus one, which is how many numbers are between them.
When I p new_arr inside my each loop, it has the correct array: [1,1] in the first case, [4,4] in the next case and [5,5] in the last case. But when I exit the each loop, the array is empty again and new_arr.reduce(:+) returns nil.
I can't understand why because I defined new_arr outside the each loop. Is there some scope issue I'm missing here?
def Consecutive(arr)
arr.sort!
num_of_nums = 0
new_arr = []
i = 0
arr.each do
return if i == arr.length - 1
num_of_nums = (arr[i+1] - arr[i]) - 1
new_arr << num_of_nums
i+=1
p new_arr
end
new_arr.reduce(:+)
end