From: Josh Cheek Date: 2012-01-24T20:45:31+09:00 Subject: Re: Dynamically creating variables --f46d041825ce1d304c04b744ae68 Content-Type: text/plain; charset=ISO-8859-1 On Tue, Jan 24, 2012 at 5:13 AM, Tris Hoar wrote: > Hi all, > > I'm fairly new to Ruby, and programming in general (though I'm reasonably > proficient at shell scripting) so sorry if this is a dumb question. > > I'm trying to write a script for an SNMP poller but I'm getting stuck > trying to work out how to create my variables. The script will be > processing a CSV of unknown length. It might be just 2 servers or it could > be up to 20. I cant work out how I can find the list of servers from the > CSV and then create variables for each one that I can keep track off > through out the programs life to out put what I want. > this is what I've created so far > http://pastebin.com/bLPbnRv4 > I envision it parsing a CSV like this > > -- > host,port,community,cluster,**shortName,type,rpsTotal,** > clientTotal,serverTotal > 172.16.0.1,161,Public,Library,**mwg1,mwg7,0,0,0 > 172.16.0.1,161,Public,Library,**mwg2,mwg7,0,0,0 > -- > after each run, it will need to update the CSV with the results of the > last poll as those are used to calculate the average throughput between > each time the script is called. > > The whole process will be called as a cron job, and will be outputting an > HTML file. > > Reading around has not really helped me as I've not found any examples of > others doing this, though I cant imagine others are not. > > If any one can give me some pointers, that would be really helpful. > > Thanks, > > Tris > > ***************************************************************** > This email and any files transmitted with it are confidential > and intended solely for the use of the individual or entity to whom they > are addressed. If you have received this email in error please notify > postmaster@bgfl.org > > The views expressed within this email are those of the individual, and not > necessarily those of the organisation > ***************************************************************** > > > So you can use CSV.parse and give it a string or a stream, or you can use CSV.foreach and give it a path to a file. Docs are here http://rubydoc.info/stdlib/csv/frames In Ruby, you can iterate over collections (e.g. 2..20 servers). A CSV file is a collection of rows. If we tell it the CSV has headers, it will present each row with a hash interface so that we can access the elements by name. csv = < true do |row| host = row['host'] port = row['port'] # etc proxy = Proxy.new host, port # etc proxy.write_stats # or something end --f46d041825ce1d304c04b744ae68--