Fibonacci in Ruby

So finally we get to Ruby. Is it a ghetto? I don’t know about that, but I do know that writing our simple Fibonacci program in Ruby was a piece of cake. Before we get to the good stuff, though, I’d like to recap where we are, and what we’ve done so far. Here’s a list of the Fibonacci project programs so far:

So this is our sixth version of the simple sequence generator, this time in Ruby

#!/usr/local/bin/ruby

# In Ruby, we define a function with def…end functions can accept parameters,
# but don’t have to, and you can leave off the parenthesis if your function does
# not need them.

def main
  printf "\nHow many numbers of the sequence would you like?\n"

  # Here, STDIN is a constant, but like everything in Ruby, it’s also a class, so
  # we use the readline method to get our input. to_i casts our input to an integer

  n = STDIN.readline.to_i
  fibonacci(n)
end

# Here is a good example of something that is cool about Ruby. The times method
# works just like it sounds, it will do something n times. As in Perl and Python,
# we don’t need a temp variable here to swap the values for a and b.

def fibonacci(n)
  a,b = 0,1
  n.times do
    printf("%d\n", a)
    a,b = b,a+b
  end
end

main

HTML code generated by vim-color-improved v.0.3.2.Download this code: fibonacci.rb

The next installment will be another popular language. Stay tuned to see Fibonacci in Java.

Leave a Reply