小编Wah*_*h.P的帖子

如何在Ruby中编写递归阶乘函数?

我只需要一些有关如何在Ruby中编写递归阶乘函数的帮助。我有以下Lisp代码,但我想在Ruby中做同样的事情。

(defun factorial (N)
    (if (= N 1) 1
        (* N (factorial (- N 1)))))
Run Code Online (Sandbox Code Playgroud)

ruby lisp recursion factorial

4
推荐指数
1
解决办法
72
查看次数

Ruby-如何打印数组的实际索引号,而不是该索引的值

有一个简单的问题。

我想放置数组的索引号,而不是数组索引的实际值。因此,如果array [0] = book1,我想放入0,而不是book1。我怎样才能做到这一点?

更具体地说,如果相关,在我的任务中,我要循环打印阵列中的每个专辑,但也想打印每个专辑的编号。

index = 0
    while index < albums.length
        print_album(albums[index])
        index += 1
    end
Run Code Online (Sandbox Code Playgroud)

ruby arrays

0
推荐指数
1
解决办法
50
查看次数

为什么在此代码中出现“ not a number”错误?

我只是希望有人可以通过以下代码帮助我:

def write(aFile, number)
  index = 1
  while (index < number)
   aFile.puts(index.to_s)
   index += 1
  end
end

def read(aFile)

  count = aFile.gets
  if (is_numeric?(count))
    count = count.to_i
  else
    count = 0
    puts "Error: first line of file is not a number"
  end

  index = 0
  while (count < index)
    line = aFile.gets
    puts "Line read: " + line
  end
end

# Write data to a file then read it in and print it out
def main
  aFile = File.new("mydata.txt", "w") …
Run Code Online (Sandbox Code Playgroud)

ruby debugging file

0
推荐指数
1
解决办法
66
查看次数

标签 统计

ruby ×3

arrays ×1

debugging ×1

factorial ×1

file ×1

lisp ×1

recursion ×1