[英]How do I output loops to a text file in ruby?
I have searched for this a lot and most articles relating to this are about php and python. 我已经搜索了很多,与此相关的大多数文章都是关于php和python的。 However they were not actually answering my question.WHEN I OPEN A TEXT FILE I WANT TO BE ABLE TO SEE THE OUTPUT THERE.I have already tried the method below.
但是他们实际上并没有回答我的问题。当我打开一个文本文件时,我希望能够看到那里的输出。我已经尝试了以下方法。 The code ran with no errors but it didn't output to the file "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()*
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
I think the sequence of your code is a little bit wrong. 我认为您的代码顺序有些错误。
You should instead; 您应该改为;
this
function this
函数 Example: 例:
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
Output: 输出:
1
1个
33
55
77
99
1111
1313
1515
1717
1919
You should also be capturing potential IO errors, this is a fairly common practise. 您还应该捕获潜在的IO错误,这是一种很常见的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.