I’m trying to capture values from the Fibonacci method and concatenate it to an array. However, rather than assigning every value from the loop to the array, it’s returning only the last value. Is there any way around this? Thank you.
def fib_up_to(max)
i1, i2 = 1, 1
while i1 <= max
yield i1
i1, i2 = i2, i1+i2
end
end
def capture_arr(val)
$a = []
$a << val
end
fib_up_to(1000) do |f|
capture_arr(f)
end
p $a # => [987]
In
capture_arr, you’re resetting the array to empty on each call, before adding an element to it. Try this instead: