emj emj - 2 months ago 21
Ruby Question

Ruby class variable initial value

In

PHP
I write:

Class Test{
public $a=100;
}

$a=new Test();
echo $a->a; //prints 100


It prints
100
, but In ruby when I write:

class Test
@a=100
attr_accessor :a
end

a=Test.new
puts a.a #=> prints nil


a
is nil and it prints
nil
. Why?

Answer

You're mixing things a bit.

What you've defined with @a = 100 is a class instance variable.

What you're going to have access to with attr_accessor :a is an instance variable @a.

Class instances DO NOT have access to their class' instance variables.

Example of instance variable usage:

class A
  def initialize a
    @a = a
  end
  attr_accessor :a
end

instance = A.new(2)
#=> 2
instance.instance_variables
#=> [:@a]
instance.a
#=> 2

Example of class instance variable usage:

class A
  @a = 1
  class << self
    attr_accessor :a
  end
end

A.a
#=> nil
A.a = 2
#=> 2
A.a
#=> 2