1

I've written this code that makes sense to me but it doesn't seem to work no matter what. This is what I've got:

def fib(places)

     a = 0
     b = 1

     while a < places do
          puts a + "\n"
          a = b
          b = a + b
     end
end

puts fib(1000)
Lamb
  • 63
  • 1
  • 7
  • 1
    Notice you don't need this `puts a + "\n"`, 'cause puts already changes the line after printing the value given. If you were using `print a` then you'd need to force the line changing. – Ed de Almeida Dec 04 '16 at 15:23
  • 1
    When asking about code you have written which is not working correctly, it is necessary to describe in detail what exactly does not work (i.e. quote any errors, describe erroneous behavior, ...) and compare this to what you would expect the code does. Please have a look at [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) for guidance on how to ask a great question that will result in answers actually helping you solve your problem and absolves from wasting their time on guessing what might be the issue. – Holger Just Dec 04 '16 at 16:04

3 Answers3

4

I assume that your places parm is used to place a limit on the maximum fibonacci value displayed.

I got good results with:

def fib(places)

  a = 0
  b = 1

  while b < places do
    puts b

    a,b = b,a+b
  end
end

fib(1000)

Yielded:

1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
Peter Camilleri
  • 1,882
  • 15
  • 17
1
def fib(num)
   i, j = 0, 1
   while i <= num
     puts i
     i, j = j, i + j
   end
end

Or

def fibonacci( n )
  return  n  if ( 0..1 ).include? n
  ( fibonacci( n - 1 ) + fibonacci( n - 2 ) )
end
puts fibonacci( 5 )
# => 5

This might help

def fibonacci( n )
    return  n  if n <= 1 
    fibonacci( n - 1 ) + fibonacci( n - 2 )
end 
puts fibonacci( 10 )
# => 55
user126885
  • 157
  • 1
  • 2
  • 10
1

2 problems :

  • a + "\n" : a is a number, "\n" is a string. You cannot add them without converting one first. Should 1 + "2" be 12 or 3? You need to make it clear for Ruby. Use puts "#{a}\n" or just puts a
  • a = b followed by b = a + b is basically just b = 2*b, which isn't what you want.
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124