On 5/10/07, Bernd <burnt99 / hotmail.com> wrote:
> Hi,
> I wrote a code like this.
>
> class ABC
>   attr_accesor :first, :second
> end
>
> when I wrote the following:
>
> x = ABC.new
> x.first = "test"
> puts x.instance_variables
>
> the output was only
>
> @first
>
> Is there a possibility to get also the unassigned variables? I mean,
> they exist, but they are only nil.

Ruby has no concept of 'declaring' instance variables (or any other
variable for that matter).  attr_accessor simply generates getter and
setter methods. The instance variable won't exist in a particular
instance until you call the setter, or directly assign to the instance
variable, such as in the initialize method.

In Ruby, instance variables don't exist until they are assigned.
Non-existant instance variables evaluate to nil, but just mentioning
them doesn't bring them into existance.

irb(main):001:0> class A
irb(main):002:1>   attr_accessor :i
irb(main):003:1>   end
=> nil
irb(main):004:0> a = A.new
=> #<A:0xb7b5aca4>
irb(main):005:0> a.instance_variables
=> []
irb(main):006:0> a.i
=> nil
irb(main):007:0> a.instance_variables
=> []
irb(main):008:0> a.i = "foo"
=> "foo"
irb(main):009:0> a.instance_variables
=> ["@i"]



-- 
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/