我将以下方法放在一起,以便 (1) 在数组中生成一个斐波那契序列,直到特定索引值,然后 (2) 返回给定索引的该序列中所有值的乘积。
当我将 master_num 值增加到 4 以上时,我的问题似乎出现了。在此之前,序列生成和产品方法都有效。我很确定我的问题与我脑海中关于 Ruby 如何索引序列数组的错误有关......
require 'pry' #optional, i use pry to debug
master_num = 5
def gen_fib_sequence_up_to_index num
rec_gen_fib_values num, []
end
def rec_gen_fib_values num, full_array
start_array = [1,1]
count = 0
if num < start_array.size
num
end
until start_array.size == num
next_element = start_array[count] + start_array[count + 1]
start_array.push(next_element)
count += 1
end
return start_array
end
p gen_fib_sequence_up_to_index master_num
def fib_sequence_product sequence_array
product = 1
sequence_array.each do |i|
product = product * sequence_array[i]
#binding.pry
end
product
end
p fib_sequence_product gen_fib_sequence_up_to_index master_num
非常感谢您的意见和建议。