From: Trans Date: 2008-04-24T23:28:41+09:00 Subject: Re: Hash keys On Apr 24, 9:11 am, Tim Wolak wrote: > Morning, > > I am working on some code to gather accounts and their balances from a text > file and have a question about adding that data to a hash. While checking > to see if the account number is a key in the existing hash using > has_key?(key), canšt I use the variable that has the account number in it or > do I have to use the actual account number? When I run my code to check it I > get undefined method `has_key?' for nil:NilClass. I ran a test using just > the account number in irb and it works but I would think you could use a > variable to iterate of my list of account numbers.... Thanks in advance > > class Info > attr_reader :acct, :money > > def initialize(filename) > @acct = File.new(filename, "r") > end > f = Info.new("Balances20080415.txt") > act = f.acct > act.each do |list| > #covert me to a string > futbal = list.to_s > #Pull accounts > office = futbal[21..23] > if office == "RPT" > next > else > acctnum = futbal[24..28] > lv = futbal[217..230] > lvind = futbal[215..215] > lvadd = lvind+lv > lvadd.to_f/100 > end > #if Negitave vlaues > if lvind == "-" > lvnegfloat = lv.to_f/100 > #print acctnum," ",lvind, lvnegfloat, "\n" > #puts lvadd > sktylist = Hash.new("") > #if(sktylist.has_key?(23)) > # sktylist = { acctnum => lvind,lvnegfloat } > > sktylist[acctnum] = lvind,lvnegfloat > sktylist.each { |key, value| puts "#{key} equals #{value}" } > #else Positive Values > > elsif sktylist.has_key?('acctnum') > puts "found #{key}second key" > #lvposflt = lv.to_f/100 > > #print acctnum, " ", lvposflt, "\n" > end > end > > end Your if clauses looked messed up. The no method error doesn't have anything to do with the key of has_key. You actually have no hash to speak of. T.