Using Ruby's inject to calculate a fibonacci number

Another twist to a common interview question. This time we’ll extend Ruby’s Integer base class so that we can do something like this:

  1. >> 0.fib
  2. => 0
  3. >> 1.fib
  4. => 1
  5. >> 29.fib
  6. => 514229


  1. class Integer
  2.  
  3. def fib
  4. return 0 if self == 0
  5. return 1 if self <= 2
  6. (self - 2).times.inject([1, 1]) { |memo, value| memo = [memo.last, (memo.first + memo.last)] }.last
  7. end
  8. end

The standard recursive answer will usually suffice in an interview:

  1. class Integer
  2.  
  3. def fib
  4. return self if self < 2
  5. (self - 2).fib + (self - 1).fib
  6. end
  7.  
  8. end

I’d just expect the candidate to be aware of the limitations of this approach. I like to pose this question during an interview.

Posted on Feb 11, 2011 | filed under Ruby | 0 comments

Join the Discussion

URLs and email addresses will be converted to links and line breaks will be converted to paragraphs. Your email address is used only to display your Gravatar, and will never be displayed.

All HTML tags are disabled, except for two exceptions:

To display formatted code, use the <code> tag. By default, code between the tags is interpreted as Ruby, however, you may use the format <code:language> to change the default interpreter. The languages currently supported are Ruby, C, HTML and Delphi.

Using the <quote> tag, you may highlight quoted text in a formatted box.

  verification text
  Please type the text you see in the image above:
  or