我已经搜索了很多,大多数与此相关的文章都是关于php和python的。然而他们实际上并没有回答我的问题。当我打开文本文件时,我想看看那里的输出。我已经尝试过以下方法。代码运行时没有错误,但没有输出到文件“filename”。
def this()
i = 0
until i>=20
i += 1
next unless (i%2)==1
puts i
end
end
filename = ARGV
script = $0
that = puts this
txt = File.open(filename,'w')
txt.write(that)
txt.close()*
答案 0 :(得分:0)
def this(file)
i = 0
until i>=20
i += 1
next unless (i%2)==1
# Normally 'puts' writes to the standard output stream (STDOUT)
# which appears on the terminal, but it can also write directly
# to a file ...
file.puts i
end
end
# Get the file name from the command line argument list. Note that ARGV
# is an array, so we need to specify that we want the first element
filename = ARGV[0]
# Open file for writing
File.open(filename, 'w') do |file|
# call the method, passing in the file object
this(file)
# file is automatically closed when block is done
end
答案 1 :(得分:0)
我认为你的代码序列有点不对劲。
你应该改为;
this
函数示例:强>
def this(file)
i = 0
until i>=20
i += 1
next unless (i%2)==1
file.puts(i)
end
end
# Main
begin
file = File.open('hello.txt','w')
this(file)
rescue IOError => e
puts "oops"
ensure
file.close()
end
<强>输出:强>
1
3
5
7
9
11
13
15
17
19
您还应该捕获潜在的IO错误,这是一种相当常见的做法。