Explanation needed for this Ruby challenge -


i need understanding code:

def simpleadding(num)   sum = 0   (num + 1).times |x|     sum = sum + x   end   return sum end  simpleadding(12) #=> 78 simpleadding(140) #=> 9870 

i not sure of method. why method written way is? why sum on first line set 0? , why sum = sum + x used on third line?

in ruby, def keyword delimits start of method, in case named simpleadding. takes 1 argument (in parentheses) named num.

in method body, variable sum given initial value of 0.

the line containing (num + 1).times |x| tells ruby execute code between do , end keywords set number of times (an iterator), in case num + 1. remember, num represents value received in form of argument when method called.

on next line, variable sum (initialized 0 @ beginning of method) assigned value of plus x.

next line, our iterator ends.

finally, return value stored inside of variable sum.

and, end of our method.

enjoy learning ruby!


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -