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

Technology CommunityCategory: RubyWrite a single line of Ruby code that prints the Fibonacci sequence of any length as an array.
VietMX Staff asked 3 years ago

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.

Note: inject is an alias of reduce