From: Sean O'Dell Date: 2004-06-22T03:41:08+09:00 Subject: Re: newbie problem with a hash On Monday 21 June 2004 11:08, Graham Nicholls wrote: > I've got a file which I've read in and split to make a hash like this: > > > def initialize(fname) > @data=Hash.new > begin > IO.foreach(fname) do |line| > key,value=line.chomp.split(":") > @data[key]=value > end > end > > This gives a hash keyed on the first field of the file, where : is the > separator. (NB How do I handle : in the data - prompt to self!) > > But when I try to get the value associated with that key by a fetch, I get > and IndexError: > > def get_datum(datid) # Typical datid is $01 - I've stripped off the colon. > if $debug > print("Getting data for id [#{datid}]\n") # Prints $01 > end > > begin > #@data.fetch("$01") - this works OK, > @data.fetch(datid) # This causes an IndexError > rescue IndexError => err > print("No data for key [#{datid}] : #{err}\n") > @data.each do |key,val| > printf("Key [%s] => [%s]\n",key,val) # Shows $01 => avalue > (amongst others) > end > exit(NO_DATA) > end > end > > I'm racking my brains, but to no avail. If I put the key in as a literal, > it returns, but using the datid variable, I get an IndexError. How are you calling get_datum? Show us the line where you call it that gives you that error. Sean O'Dell