18. Blocks (Methods, Blocks & Sorting)


#1

This is my answer to no.18;

my_array = [1, 2, 3, 4, 5]
sum = 2
my_array.each do |n|
sum = n * n
end
puts sum

Answer returns
25
nil

"

Oops, try again.
It looks like your block doesn't print the square of each number in my_array to the console using 'puts'.

What is the correct answer?


#2

The reason why your code does not output all the squares for each value of the array, is because your puts sum is outside the array, thus only printing the last value of sum. The corrected code should look like this

my_array = [1, 2, 3, 4, 5]
sum = 2
my_array.each do |n|
sum = n * n
puts sum
end


#3

Thank you! It's sorted!


#21