我是ruby的新手,我遇到了一个错误,我无法在谷歌或堆栈溢出中找到答案。
我正在尝试将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'数据类型。
答案 0 :(得分:2)
对于您发布的错误,这是因为find_fib
方法的终止条件返回anumber
Fixnum
类型( find_fib(anumber - 1) + find_fib(anumber - 2 ))
。此返回值用于以前的递归:
Array + Fixnum
在这里,您将调用def find_fib(anumber)
return [anumber] if anumber <= 1
...
,这会导致类型检查错误。将终止条件更改为以下可能会删除该错误。
find_fib
顺便说一句,你{{1}}无法按预期工作,你可能需要进一步调整算法实现。
答案 1 :(得分:1)
您的方法存在许多问题:
def find_fib(anumber)
return anumber if anumber <= 1
(find_fib(anumber - 1) + find_fib(anumber - 2)) # 1
# ETC...
@fib.push(number) # 2 and 3
end
您在这里计算斐波纳契数,但是您没有将值赋给变量, 所以你基本上扔掉了这个号码。
返回Ruby函数中评估的最后一个语句,除非你创建了一个
明确的return
语句就像你的第一行一样。作为Arie Shaw points out,
最后一行返回一个数组对象,而第一行返回一个数字,所以你就是这样
试图调用Array + Fixnum
,这不是一个定义的操作。
您已将number
推入@fib
阵列,但该变量未被分配到
在任何地方都有价值。
如果你想要一个生成第一个n
斐波纳契数的数组的方法,这里有一种Ruby方法可以做到:
def fib(n)
(n == 1) ? [0] : (2..(n-1)).each_with_object([0,1]) { |i,a| a[i] = a[i-2] + a[i-1] }
end