From: Robert Klemme Date: 2004-02-26T20:04:53+09:00 Subject: Re: Why don't $global and @instance variables need declaration? "David Garamond" schrieb im Newsbeitrag news:403DC272.10009@zara.6.isreserved.com... > Sorry if the answer is obvious, but I can't find a satisfactory or more > verbose explanation about this. The only thing I found is from the > Ruby's User Guide: > > "As with globals, instance variables have the nil value until they are > initialized. Instance variables of ruby do not need declaration. This > implies a flexible structure of objects. In fact, each instance variable > is dynamically appended to an object when it is first referenced." > > Could someone explain the above? How is it more flexible? You don't need the declaration. That saves typing and also you can add them at runtime as you like: irb(main):003:0> class Foo irb(main):004:1> def set(name, val) irb(main):005:2> instance_eval "#{name} = val" irb(main):006:2> end irb(main):007:1> irb(main):008:1* def get(name) irb(main):009:2> instance_eval name irb(main):010:2> end irb(main):011:1> end => nil irb(main):012:0> irb(main):013:0* f=Foo.new => # irb(main):014:0> f.set "@foo", "bar" => "bar" irb(main):015:0> f.get "@foo" => "bar" irb(main):016:0> f.set "@hello", "world" => "world" irb(main):017:0> f.instance_variables => ["@hello", "@foo"] irb(main):018:0> If you would need to declare globals then you either need to include a declaration for each global you need or you had to add code in each place that would do the declaration on the fly when needed. That's tedious and error prone. > Also, how do > we differentiate between an unitialized global/instance variable and a > variable that has explicitly been set to 'nil'? Typically you don't. There are certain situations where you can use "defined?" but these are rare. AFAIK it's seldom used. The more usable option is to use "global_variables": irb(main):002:0> puts global_variables $-w $stderr $LOAD_PATH $< $-0 $+ $-p $$ $-i $deferr $~ $! $-v $stdout $_ $-K $-F $SAFE $* $-I $/ $' $-d $FILENAME $defout $@ $VERBOSE $stdin $. $KCODE $; $binding $0 $: $, $` $DEBUG $> $-a $" $\ $= $-l $? $& => nil irb(main):003:0> Regards robert