-1

I need some help understanding this code:

def SimpleAdding(num)
  sum = 0
  (num + 1).times do |x|
    sum = sum + x
  end
  return sum
end

SimpleAdding(12) #=> 78
SimpleAdding(140) #=> 9870

I am not sure of the method. Why is the method written the way it is? Why is sum on the first line set to 0? And why is sum = sum + x used on the third line?

sawa
  • 165,429
  • 45
  • 277
  • 381
Tonyhliu
  • 225
  • 1
  • 2
  • 9

1 Answers1

1

In Ruby, the def keyword delimits the start of a method, in your case named SimpleAdding. It takes one argument (in the parentheses) named num.

In the method body, the variable sum is given the initial value of 0.

The line containing (num + 1).times do |x| tells Ruby to execute the code between the do and end keywords a set number of times (an iterator), in this case num + 1. Remember, num represents the value received in the form of an argument when the method was called.

On the next line, the variable sum (initialized to 0 at the beginning of the method) is assigned the value of itself plus x.

Next line, our iterator ends.

Finally, we return the value stored inside of the variable sum.

And, the end of our method.

Enjoy learning Ruby!

Hatchet
  • 5,320
  • 1
  • 30
  • 42
  • Thanks for helping Hatchet! Appreciate it! – Tonyhliu Jan 18 '16 at 00:39
  • @tbunz If you feel it would be helpful to others, you can [mark my answer as accepted](http://meta.stackexchange.com/q/5234/179419) by clicking the check mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer (me) and yourself. There is no obligation to do this. – Hatchet Jan 18 '16 at 00:50
  • One more quick question @hatchet, what does =~ mean in ruby? It just means matches right? – Tonyhliu Jan 22 '16 at 02:13
  • @tbunz More specifically, it matches a string to a regular expression: https://stackoverflow.com/questions/3025838/what-is-the-operator-in-ruby – Hatchet Jan 22 '16 at 02:56