简体   繁体   English

如何将循环输出到Ruby中的文本文件?

[英]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; 您应该改为;

  1. Do whatever you want eg process ARGV (This step is fine) 做任何您想做的事,例如处理ARGV(这一步很好)
  2. Open the file - this returns you the file handler 打开文件-这将返回文件处理程序
  3. Pass the file handler to the this function 将文件处理程序传递给this函数
  4. Write the content 写内容
  5. Close the file 关闭档案

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个
3 3
5 5
7 7
9 9
11 11
13 13
15 15
17 17
19 19

You should also be capturing potential IO errors, this is a fairly common practise. 您还应该捕获潜在的IO错误,这是一种很常见的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM