user2730388
user2730388

Reputation: 11

Can I declare a Ruby class member?

In Java, I can declare a public member of a class, but it seems I cannot do this in Ruby.

class Person
  @a = 1

  def hello()
    puts(@a)
  end
end

p = Person.new
p.hello()  
#nil

Why is the output nil rather than 1?

Upvotes: 1

Views: 228

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118289

Because instance variable @a is not initialized for the instance pr.

class Person
@a = 1
  def hello()
    puts(@a)
  end
end

pr = Person.new
pr.instance_variable_get(:@a) # => nil

Now see below:-

class Person
  def initialize(a)
    @a=a
  end
  def hello()
    puts(@a)
  end
end

pr = Person.new(1)
pr.instance_variables # => [:@a]
Person.instance_variables # => []
pr.instance_variable_get(:@a) # => 1
pr.hello # => 1

Instance variables

An instance variable has a name beginning with @, and its scope is confined to whatever object self refers to. Two different objects, even if they belong to the same class, are allowed to have different values for their instance variables. From outside the object, instance variables cannot be altered or even observed (i.e., ruby's instance variables are never public) except by whatever methods are explicitly provided by the programmer. As with globals, instance variables have the nil value until they are initialized.


Now look here:-

class Person
@a = 1
  def self.hello()
    puts(@a)
  end
end
Person.hello # => 1
Person.instance_variables # => [:@a]
Person.new.instance_variables # => []

So in this example @a is the instance variable of the object Person,not the instances of Person.Very good tips is here - Class Level Instance Variables.

Upvotes: 1

Related Questions