【问题标题】:Printing to console and writing to a file at the same time Ruby [duplicate]打印到控制台并同时写入文件Ruby [重复]
【发布时间】:2015-03-13 07:29:45
【问题描述】:

我正在尝试用 ruby​​ 编写一些代码,这将允许我将测试的输出打印到控制台并将相同的输出打印到文件中。我目前在下面这样做的方式似乎是多余的。

f = File.open("ExampleText.txt", "w")

if example1 > example2 then
    print("Do it")
    f.print("Do it")
else 
    print("Don't do it")
    f.print ("Don't do it")
end

【问题讨论】:

    标签: ruby output


    【解决方案1】:

    您可以编写一个简单的方法来执行您正在做的事情,并在您的条件下调用该方法。这里:

    def write_and_display(str, file)
      puts str
      file.puts str
    end
    
    f = File.open("ExampleText.txt", "w")
    if example1 > example2
      write_and_display("do this", f)
    else
      write_and_display("dont do it", f)
    end
    

    另外,您还可以编写一个伪 IO 类,该类将写入多个 IO 对象。在这个 SO 上讨论的东西:https://stackoverflow.com/a/6407200/3035830

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 2020-04-10
      相关资源
      最近更新 更多