Question:

Write a single line of Ruby code that prints the Fibonacci sequence of any length as an array.

(Hint: use inject)

Answer:

There are multiple ways to do this, but one possible answer is:

(1..20).inject( [0, 1] ) { | fib | fib << fib.last(2).inject(:+) }

As you go up the sequence fib, you sum, or inject(:+), the last two elements in the array and add the result to the end of fib.


Keywords:

© 2017 QuizBucket.org