2

I am writing a method that returns the nth element in the Fibonacci sequence, but am running into an unexpected end error.

def fib_seq(n)

  a = [0]

  n.times do |i|
    if i==0
      a[i] = 0
    else if i==1
      a[i] = 1
    else
      a[i] = a[i-1] + a[i-2]
    end  
  end

  return a[n]
end

puts fib_seq(4)

Any tip on what I can be screwing up on?

1
  • 2
    Just an unrelated note: The naming convention for Ruby is to use lowercase_with_underscores for method and variables. Commented Sep 20, 2012 at 0:15

3 Answers 3

4

Assuming you are trying to return the nth (and not the (n-1)th, i.e. fib(1) = 0 NOT fib(0) = 0).

I fixed it by changing:

else if i==1

to

elsif i==1

(AND)

return a[n]

to

return a[n - 1]

So your final code should look like:

def fibSeq(n)

  a = [0]

  n.times do |i|
    if i==0
      a[i] = 0
    elsif i==1
      a[i] = 1
    else
      a[i] = a[i-1] + a[i-2]
    end  
  end

  return a[n-1]
end

puts fibSeq(4)

Per your comment below, the following code will work:

def fibSeq(n)

  a = [0]

  (n+1).times do |i|
    if i==0
      a[i] = 0
    elsif i==1
      a[i] = 1
    else
      a[i] = a[i-1] + a[i-2]
    end  
  end

  return a[n]
end

puts fibSeq(4)

If you want to output the fibs as a list then use:

return a[0..n]

Instead of

return a[n]
Sign up to request clarification or add additional context in comments.

3 Comments

Which is the difference with else if and elsif in Ruby? I'm sure you answer is correct. I just want to know.
elsif is what a c-style programmer (let's just say that means C, C++, Java, C#, etc...) would know as else if. I believe that in ruby else if actually does two things it, (1) acts as the else from the above if statement, then it (2) acts as an if.
What if I want my sequence to be 0, 1, 1, 2, 3...?
2

Very optimised code

Version 1

def fib(n, cache)
  return 1 if n <= 2
  return cache[n] if cache[n]
  cache[n] = fib(n - 1, cache) + fib(n - 2, cache)
end

cache = {}
puts fib(5,cache)

Version 2

def fib(n)
 return 1 if n <= 2
 fib_index = 3
 a, b = 1, 1
 while fib_index <= n
   c = a + b
   a = b
   b = c
   fib_index += 1
 end
c
end

puts fib(100)

Comments

1

If you go recursive this is the seudo-code:

fib(n) {
    if n = 0 -> return 0
    else if n = 1 -> return 1
    else -> return fib(n-1) + fib (n-2)
}

1 Comment

Yeah recursive is good option but it will take good amount of time for n = 100

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.