Monday, December 27, 2010

Ruby Here_and_there_3 - Learning Classes with Ruby

This is a small program that can ping hosts listed in a file Server list,

Ruby makes it so simple,

#!/usr/bin/ruby

require 'rubygems'
require 'net/ping'

class Server
def initialize(server1)
@server1=server1
end

def ping_host
Net::Ping::TCP.econnrefused = true
o = Net::Ping::TCP.new @server1
if o.ping?
puts @server1 + " Can be reached"
else
puts @server1 + " Can not be reached"
end
end

end

File.readlines('serverlist').each do |server|
host1=Server.new(server.chomp)
host1.ping_host
end


host1 is the object getting created.

Then we call the method within the class Server , i.e. ping_host to work with host1.


No comments:

Post a Comment