【发布时间】:2014-03-31 01:47:36
【问题描述】:
我是 ruby 的新手,我遇到了一个错误,我无法在 google 中找到答案,或者堆栈溢出。
我正在尝试将 fibinachi 序列的前 10 个值放入一个数组中,如下所示:
#@fib=[] #Maybe try creating the array differently?
@fib=Array.new
foo=42
puts "foo is of type #{foo.class}"
@fib.push(42) #Testing the array
puts @fib #Show the test
def find_fib(anumber)
return anumber if anumber <= 1
( find_fib(anumber - 1) + find_fib(anumber - 2 ))
#@fib.push(anumber.to_i) #Maybe I need to specify it is an integer http://stackoverflow.com/questions/11466988/ruby-convert-string-to-integer-or-float
puts "anumber is of type #{anumber.class}"
puts "They array is of type #{@fib.class}"
puts "a number is #{anumber}"
@fib.push(anumber) #<= this line fails
end
puts find_fib(10)
我收到以下错误:
...`+': no implicit conversion of Fixnum into Array (TypeError)
.......
foo is of type Fixnum
42
anumber is of type Fixnum
They array is of type Array
a number is 2
[Finished in 0.3s with exit code 1]
有人可以向我解释foo 和anumber 之间有什么不同,这会阻止我追加到数组中吗?毕竟,它们都是“Fixnum”数据类型。
【问题讨论】:
-
顺便说一句,Ruby 的惯例是使用 2 空格缩进,而不是 4 空格缩进。
-
@fib.push(number) #<= this line fails看起来像是错字。应该是@fib.push(anumber)。 -
Johnsyweb 感谢您指出这一点。错字只存在于 SO 上,而不存在于我的本地副本上。我在问题中修复了它。
-
@spuder 顺便说一句,我认为您的原始算法的问题之一可能是每个递归调用都返回一个数组,该数组表示斐波那契数的加法操作数,而不仅仅是总和的斐波那契数对于那个子序列。不过,这只是一种预感,我不能 100% 确定这是问题所在。
标签: ruby arrays recursion types primitive-types