4

I'm a Ruby newbie. Have a very basic question about static and instance variables.

class Test

  def self.init
    @@var_static = 1
    @member = 2
  end

  def self.print
    puts "@@var_static: #{@@var_static}"
    puts "@member: #{@member}"
  end

end

Test.init
Test.print

Why does the code above allow initialization of a member variable: @member, inside the static method: Test::init ? My understanding was that usage of @member will throw an error because it is not tied to any instance of class Test. But no error is thrown.

2 Answers 2

3

A class is an instance of an object though, and can have instance variables just like any other object:

>> Fixnum.class
=> Class

Fixnum the class is an instance of Class!

Sign up to request clarification or add additional context in comments.

6 Comments

Which class is the @member variable tied to, and how can I find it?
I don't understand your question. When you define a class you are creating a single instance of Class. Test the class you just defined is the instance which has @member.
Try: Test.instance_variable_get('@member')
it's all about the context your code is evaluated in. if you define a method with self.something then you are in the context of the class you are currently defining. so the "member" variable is a member of the class.
That is very much unlike Java. Trying to access a member variable from a static method will give a compile error. You have to have an instantiated object before you can get the instance variables.
|
1

A good article explaining this is here: http://railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.