【问题标题】:Why can't I append to the end of an array recursively in Ruby?为什么我不能在 Ruby 中递归地追加到数组的末尾?
【发布时间】: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]

有人可以向我解释fooanumber 之间有什么不同,这会阻止我追加到数组中吗?毕竟,它们都是“Fixnum”数据类型。

【问题讨论】:

  • 顺便说一句,Ruby 的惯例是使用 2 空格缩进,而不是 4 空格缩进。
  • @fib.push(number) #&lt;= this line fails 看起来像是错字。应该是@fib.push(anumber)
  • Johnsyweb 感谢您指出这一点。错字只存在于 SO 上,而不存在于我的本地副本上。我在问题中修复了它。
  • @spuder 顺便说一句,我认为您的原始算法的问题之一可能是每个递归调用都返回一个数组,该数组表示斐波那契数的加法操作数,而不仅仅是总和的斐波那契数对于那个子序列。不过,这只是一种预感,我不能 100% 确定这是问题所在。

标签: ruby arrays recursion types primitive-types


【解决方案1】:

对于您发布的错误,这是因为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 不会按预期工作,你可能需要进一步调整算法实现。

【讨论】:

  • 您在两个帐户上都是对的,将 anumber 更改为 [anumber] 消除了错误。我现在可以研究的算法仍然存在问题。 gist.github.com/spuder/9885656
【解决方案2】:

你的方法有很多问题:

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
  1. 您在此处计算斐波那契数,但未将值分配给变量, 所以你基本上是在扔掉这个数字。

  2. 返回在 Ruby 函数中评估的最后一条语句,除非您创建 明确的return 声明,就像你的第一行一样。作为Arie Shaw points out, 最后一行返回一个数组对象,而第一行返回一个数字,所以你 尝试调用Array + Fixnum,这不是定义的操作。

  3. 您正在将 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

【讨论】:

    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 2017-12-23
    • 2023-04-03
    • 1970-01-01
    • 2013-11-13
    • 2013-03-21
    • 2018-03-15
    • 2023-03-02
    相关资源
    最近更新 更多