From: Robert Klemme Date: 2012-01-24T21:27:28+09:00 Subject: Re: Dynamically creating variables On Tue, Jan 24, 2012 at 12:13 PM, Tris Hoar wrote: > 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. You do not want to create variables. Instead, you use collections. With a Hash you can pick an appropriate key (e.g. IP or domain name of server). Yo could also store values in Hashes. Example 13:25:53 Temp$ ruby19 csv.rb {"172.16.0.1"=> {"host"=>"172.16.0.1", "port"=>"161", "community"=>"Public", "cluster"=>"Library", "shortName"=>"mwg1", "type"=>"mwg7", "rpsTotal"=>"0", "clientTotal"=>"0", "serverTotal"=>"0"}, "172.16.0.2"=> {"host"=>"172.16.0.2", "port"=>"161", "community"=>"Public", "cluster"=>"Library", "shortName"=>"mwg2", "type"=>"mwg7", "rpsTotal"=>"0", "clientTotal"=>"0", "serverTotal"=>"0"}} 13:26:12 Temp$ cat dat.csv host,port,community,cluster,shortName,type,rpsTotal,clientTotal,serverTotal 172.16.0.1,161,Public,Library,mwg1,mwg7,0,0,0 172.16.0.2,161,Public,Library,mwg2,mwg7,0,0,0 13:26:27 Temp$ cat -n csv.rb 1 require 'csv' 2 require 'pp' 3 4 head = nil 5 data = {} 6 7 CSV.foreach("dat.csv") do |row| 8 if head 9 tmp = {} 10 11 head.zip row do |h,v| 12 tmp[h] = v 13 end 14 15 data[row.first] = tmp 16 else 17 head = row.each &:freeze 18 end 19 end 20 21 pp data 13:26:34 Temp$ Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/