Ruby code snippets : fibonacci series

One of the best ways to start learning Ruby is to try out simple programming problems. Let us see how we can generate fibonacci series using Ruby,

# Generates a fixed length fibonacci series
class FibonacciGenerator
  # print fixed number of fibonacci series numbers specified by size
  def printFibo(size)
    x1,x2 = 0, 1
    0.upto(size){puts x1;x1+=x2; x1,x2= x2,x1} # note the swap for the next iteration
  f =
  f.printFibo(10) # print first 10 fibo numbers

This is a verbose an example. You could achieve the same in a single line!

x1,x2 = 0, 1;  0.upto(size){puts x1;x1+=x2; x1,x2= x2,x1}

Leave a Reply