2

I can’t figure out how the n.times line works in the ruby code given below, specifically what the commas mean and how the new variable is updated.

def fib(n)
  raise "fib not defined for negative numbers" if n < 0
  new, old = 1, 0
  n.times {new, old = new + old, new}
  old
end

The code works, and was code given by user pjs in response to a question about fibonacci sequences in ruby, at this stackoverflow question: Ruby Fibonacci algorithm.

I don’t understand what’s going on inside the block.

Community
  • 1
  • 1
stack888
  • 23
  • 3

2 Answers2

2

Ruby supports parallel assignment.

new, old = new + old, new

is roughly equivalent to:

temp = [new + old, new]  # right side are evaluated and stored in an array
new, old = temp          # there is a commaa in the left side
                         # so they get the value from the array, one by one
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
2

n.times { ... } will do whatever is inside the block n times. So for example, if n is 5, it's equivalent to:

new, old = 1, 0
new, old = new + old, new # new = 1+0 = 1; old = 1
new, old = new + old, new # new = 1+1 = 2; old = 1
new, old = new + old, new # new = 2+1 = 3; old = 2
new, old = new + old, new # new = 3+2 = 5; old = 3
new, old = new + old, new # new = 5+3 = 8; old = 5
old
# => 5

The other thing that may be confusing you is the parallel assignment:

new, old = new + old, new

In general, you can have:

a, b = <some-expr>, <some-other-expr>

The expressions on the right will be evaluated first, and then a will be assigned the first value, b the second. You can use this as a quick way to swap two variables without using a temp variable, for example: a, b = b, a.

Amit Kumar Gupta
  • 17,184
  • 7
  • 46
  • 64