Ruby beginner -- question regarding a challenge problem I came across

Please take a look at attached picture.

I’m having trouble understanding

sum = 0
(num + 1).times do |x|
sum = sum + x

Why did he set sum = 0. Why did he do (num + 1).times do |x|? And Why
did he do sum = sum + x?

Thanks

If you want to understand a loop, try writing down each step:

Start:
num = 3
sum = 0

Loop (num + 1) times:
This loops 4 times because #times will make x start at 0

Loop 1:
x = 0
sum = 0

Loop 2:
x = 1
sum = 1

Loop 3:
x = 2
sum = 3

Loop 4:
x = 3
sum = 6

If you want to try this out, modify the method by adding a few “puts”
lines to show the output as it works:

def SimpleAdding(num)

sum = 0
(num + 1).times do |x|
sum = sum + x
puts “x is #{x} and sum is #{sum}”
end
return sum

end

irb(main):011:0> SimpleAdding 4
x is 0 and sum is 0
x is 1 and sum is 1
x is 2 and sum is 3
x is 3 and sum is 6
x is 4 and sum is 10
=> 10

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs