G
Graham Nicholls
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.
I'd appreciate a pointer - its probably something daft - it usually is, but
I haven't got a cardboard analyst.
PS I rather like Ruby - its more elegant than Python (but don't tell anyone
in c.l.python!), IMNSHO.
Graham
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.
I'd appreciate a pointer - its probably something daft - it usually is, but
I haven't got a cardboard analyst.
PS I rather like Ruby - its more elegant than Python (but don't tell anyone
in c.l.python!), IMNSHO.
Graham