rahrahruby
rahrahruby

Reputation: 693

How do I get Ruby 'puts' to write data into a file?

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.

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

Upvotes: 11

Views: 16840

Answers (1)

Josh Lee
Josh Lee

Reputation: 177530

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

Upvotes: 32

Related Questions