如何在ruby中输出循环到文本文件?

时间:2016-07-22 01:08:12

标签: ruby file loops text

我已经搜索了很多,大多数与此相关的文章都是关于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()*

2 个答案:

答案 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)

我认为你的代码序列有点不对劲。

你应该改为;

  1. 做你想做的事,例如处理ARGV(这一步没问题)
  2. 打开文件 - 这会返回文件处理程序
  3. 将文件处理程序传递给this函数
  4. 撰写内容
  5. 关闭文件
  6. 示例:

    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错误,这是一种相当常见的做法。