def adjacent_sum(arr)
narr = []
arr.each.with_index do |num, index|
narr << (arr[index] + arr[index+1])
end
return narr
end
print adjacent_sum([3, 7, 2, 11])
#=> [10, 9, 13], because [ 3+7, 7+2, 2+11 ]
adjacent_sum([2, 5, 1, 9, 2, 4])
#=> [7, 6, 10, 11, 6], because [2+5, 5+1, 1+9, 9+2, 2+4]
I am trying to modify the narr based on input from the user. Basically trying to get all adjacent nums to sum and return a new array.
Write a method adjacent_sum that takes in an array of numbers and returns a new array containing the sums of adjacent numbers in the original array. See the examples.
I am new to Ruby and its way of thinking. I do not know which iteration method to use for this problem and I know there are many iteration methods. I COULD go the old route and just do a while loop but I want to understand the mechanics of the .each loop.
Here is the error message:
/tmp/file.rb:5:in `+': nil can't be coerced into Integer (TypeError)
from /tmp/file.rb:5:in `block in adjacent_sum'
from /tmp/file.rb:3:in `each'
from /tmp/file.rb:3:in `with_index'
from /tmp/file.rb:3:in `adjacent_sum'
from /tmp/file.rb:10:in `<main>'