-1

I want to generate fibonacci series in ruby, till the max hits a max value say 50000. I wrote the following snippet:

high = 50000
arr = [0, 1]

while arr.last < high do
  arr.inject{|a, i| arr.push(arr[-2] + arr[-1])}
end

puts arr.last

This causes the program to halt. I am actually new to ruby, Is there a good way to tackle ifs and while with inject in the same statement in ruby? What could be a better approach for the above method i am using.

user993563
  • 18,601
  • 10
  • 42
  • 55
  • Take a look at [this question](http://stackoverflow.com/questions/6418524/fibonacci-one-liner) for some other approaches to generating the Fibonacci sequence in Ruby. – mikej Jul 23 '12 at 20:34
  • 1
    question is not more about fibo sequence, its more about using conditions near inject. – user993563 Jul 23 '12 at 20:35
  • @user993563: the problem is that inject isn't useful at all for the snippet you show (generating fibonacci values). – tokland Jul 23 '12 at 20:37
  • okay, probably its my first out, so trying diff. stuff. – user993563 Jul 23 '12 at 20:37

1 Answers1

2

You are using inject for no apparent reason, while + << are enough to accumulate values:

fibs = [0, 1]
while fibs.last < 50_000
  fibs << fibs[-2] + fibs[-1]
end
fibs.last # 75025

Remember that inject folds a collection, you have no collection to fold here, you're generating one, inject won't help you.

tokland
  • 66,169
  • 13
  • 144
  • 170
  • yes, i am generating a collection, but there is simple if around that collection, continue till you hit a max, could i place the condition near inject, writing otherwise did not look to me more rubyish, it looks rather rubbish ;-) – user993563 Jul 23 '12 at 20:36