From: Robert Klemme Date: 2009-08-25T15:59:53+09:00 Subject: Re: Stuck on silly nil issue 2009/8/25 Nick Wild : > Banging my head on the desk over this.. > > I'll try to generalize my issue down to this scenario. Since I remember > always using cars back in programming classes here it goes... > > > cars["yugo"].status["available"] = 2 > > > Some thing like this is working perfectly... > > if cars["yugo"].status["available"] >   puts "There are" + cars["yugo"].status["available"].to_i + "yugos > available" > end > if cars["kia"].status["available"] >   puts "There are" + cars["kia"].status["available"].to_i + "kia > available" > end > > I get "There are 2 yugos available" > > > > But when I do this.... > > cars_to_scan = ["yugo", "kia"] > cars_to_scan.each { |carbrand| >  if cars[carbrand].status["available"] >    puts cars["yugo"].status["available"].to_i + carbrand + "available" > } > > > I hit: You have a nil object when you didn't expect it! > You might have expected an instance of ActiveRecord::Base. > The error occurred while evaluating nil.attributes > > So I tried > > if cars[carbrand.to_s].status["available"] > and also this: > unless cars[carbrand.to_s].status["available"].nil? > > same error > > I don't understand why I can use the string directly but when I try > indirectly it's hitting this error and why I'm getting a nil error when > I'm trying to use the if to check if the object is not nil. > > I'm still really baffled by certain things in ruby. Thanks in advance > for any tips or pointers. I'm sorry for the newbie question but this is > one of those dig through google and books and still come up ready to > pull your hair out little niggling things. Look at your line that starts with "puts" - it's just a silly copy and paste error. :-) Note: if you need to access a single object multiple times in the block, it is more efficient and probably also more readable to just pull it once. Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/