Fibonacci Code Golf

Note: If anybody came to my blog looking for resources that I mentioned I would post here, I will be posting code this week. For info on using a factory instead of fixtures, see this post.

At the Ruby Hoedown conference that was in Raleigh, NC this weekend, the organizers held a "Ruby Showdown" competition to give randomly selected competitors a chance to win a free ticket to a Pragmatic Studio training. One of the challenges was to code golf a Fibonacci method (meaning to implement it using as few characters as possible). Jeremy McAnally provided a base implementation:

def fibonacci(number)
  if number < 2
    number
  else
    fibonacci(number-1) + fibonacci(number-2)
  end  
end

Taking out the whitespace, this implementation is 66 characters. The method was based on a snippet of code shown earlier at the conference. which was the shortest solution at 35 characters:

def fibonacci1(number)
x=y=1;(number-2).times{x,y=y,x+y};y
end

I came up with a couple solutions which may win in an obfuscation contest, but were slightly longer. I kept the method signature the same, and I am not including it in the number of characters. My first alternative solution uses inject and comes in at 48 characters:

def fibonacci2(number)
(1..number-2).inject([1,1]){|(a,b),|[b,a+b]}[-1]
end

I wrote a couple variations that are the same length:

def fibonacci2(number)
(1..number-2).inject([1,1]){|(a,b),|[b,a+b]}[-1]
(1..number-2).inject([1]*2){|(a,b),|[b,a+b]}[-1]
(1..number-2).inject([1]*2){|(a,b),|[b,a+b]}.pop
end

My next solution uses a hash. It is the most obfuscated code I came up with, but it comes in at 42 characters:

def fibonacci3(number)
Hash.new{|h,k|k<3?1:h[k-1]+h[k-2]}[number]
end

The recursive Hash solution led to a slightly shorter proc version, shaving 2 characters, ending up at 40:

def fibonacci4(number)
p=proc{|x|x<3?1:p[x-1]+p[x-2]};p[number]
end

All the solutions pass the same set of unit tests. Code golfing may not have great benefits, but it forced me think of various features of Ruby that I could use to shorten the code.