From: Bill Kelly Date: 2003-02-20T08:33:30+09:00 Subject: Re: How to test for existence of instance variable? Hi again, From: "Paul Brannan" > Everything starts out as not being there at all: > > class Foo > def initialize > p @x #=> nil > p instance_variables() #=> [] > p defined?(@x) #=> nil > > @x = nil > p @x #=> nil > p instance_variables() #=> ["@x"] > p defined?(@x) #=> "instance-variable" > end > end > > f = Foo.new > > Ruby is not initializing @x to nil here; instead, it is giving you nil > when you try to use an instance variable that doesn't exist. Depending > on this behavior is bad style and may lead to very subtle bugs. As someone who is generally fanatical about getting better at writing programs with next-to-zero bugs in them, I'm still unclear as to why depending on the behavior of uninitialized variables defaulting to nil might lead to very subtle bugs. What you've written above with instance variables seems so analagous to me with: >> h = {} => {} >> p h['x'] => nil >> h.keys => [] >> p h.has_key? 'x' => false >> h['x'] = nil => nil >> p h['x'] => nil >> h.keys => ["x"] >> p h.has_key? 'x' => true I'm not accustomed to viewing reliance on default values for non- existent hash keys with trepidation... So I'm wondering if you have any specific 'gotcha's in mind with instance variables. (I admit i'm playing a bit 'o the Devils Advocate here.... since in actuality I always run with ruby -w ... :) Thanks, Bill