我只需要一些有关如何在Ruby中编写递归阶乘函数的帮助。我有以下Lisp代码,但我想在Ruby中做同样的事情。
(defun factorial (N)
(if (= N 1) 1
(* N (factorial (- N 1)))))
Run Code Online (Sandbox Code Playgroud) 有一个简单的问题。
我想放置数组的索引号,而不是数组索引的实际值。因此,如果array [0] = book1,我想放入0,而不是book1。我怎样才能做到这一点?
更具体地说,如果相关,在我的任务中,我要循环打印阵列中的每个专辑,但也想打印每个专辑的编号。
index = 0
while index < albums.length
print_album(albums[index])
index += 1
end
Run Code Online (Sandbox Code Playgroud) 我只是希望有人可以通过以下代码帮助我:
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)