如何让Ruby'puts'将数据写入文件?

时间:2021-05-04 20:44:36

I have the following code that I want to use to ping IP addresses and write to a file. It all works fine, except I can't get it to write to the file.

我有以下代码,我想用来ping IP地址和写入文件。一切正常,除了我无法写入文件。

server = %w'192.168.150.254
192.168.150.251
192.168.120.1
192.168.120.2'

File.open('/test/test2.out','w') do |s|
  server.each do |p|
    r = `ping -a -n 1 #{p}`
    puts r
  end
end

1 个解决方案

#1


31  

Change puts r to s.puts r. You're writing to stdout instead of to s. (See Kernel#puts and IO#puts)

更改将r放入s.puts r。你写的是stdout而不是s。 (参见Kernel#puts和IO#puts)

#1


31  

Change puts r to s.puts r. You're writing to stdout instead of to s. (See Kernel#puts and IO#puts)

更改将r放入s.puts r。你写的是stdout而不是s。 (参见Kernel#puts和IO#puts)