here is my code:

It works but I saw that people add line 2 as "sum=2". What for?


I fiddled around with this a bit and I think that some people initialized the variable before including it in the block. Basically, they set Sum = 2, which was then immediately changed to Sum = 1*1, Sum = 2*2, Sum = 3*3 etc. as the computer ran through the code. The value "2" is arbitrary - the code works whether Sum = 0 or 2 or 1000 initially. This is because, as I said, no matter what Sum is at first it immediately changes as the computer runs your code.

Your code is definitely more "intuitive" in the sense that it is more directly what our course asks for in this problem. I think the reason you saw this may have been because in some situations in other languages you need to "initialize" each variable, or assign it a value, before you use it. People who know other languages might have the habit of initializing their variables before using them. Idk, that would be my guess.


Also consider:

my_array = [1, 2, 3, 4, 5]

my_array.each {|n| puts n**2}

My understanding is as follows: "n" is the placeholder for the value provided by the current key index of "my_array". The ".each" method calls each key index in the array sequentially and automatically assigns its value to the placeholder "n". Therefore it is necessary only to describe how that value will be presented by the "puts" command, inserting the calculation there. This simplifies the code, because much of it has already been take care of by the .each method.