1 ruby arrays loops capture fibonacci
我正在尝试从Fibonacci方法中捕获值并将其连接到数组.但是,不是将循环中的每个值赋给数组,而是仅返回最后一个值.有没有办法解决?谢谢.
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]
在capture_arr,在向每个调用添加元素之前,您将在每次调用时将数组重置为空.试试这个:
def capture_arr(val)
$a ||= []
$a << val
end
Run Code Online (Sandbox Code Playgroud)