0

Ruby 1.9

I suddenly realize I don't understand how to define and initialize an instance variable in Ruby. It must be used only within a certain class and not accessible out of a class at all, so attr_accessor or attr_reader is not what I need.

class MyClass #how do I initialize it? @my_var = 'some value' def method1 #I need to do something with @my_var puts @my_var end def method2 #I need to do something with @my_var puts @my_var end end a = MyClass.new a.method1 #empty a.method2 #empty 

So I found that there is another way to do it

class MyClass #is this the only way to do it? def initialize @my_var = 555 end def method1 #I need to do something with @my_var puts @my_var end def method2 #I need to do something with @my_var puts @my_var end end a = MyClass.new a.method1 #555; it's ok a.method2 #555; it's ok 

Well, is second approach the right one?

2 Answers 2

3

each class has an initialize() method that acts similar to a constructor in other languages, instance variables should be initialized there:

class MyClass def initialize @my_var = 'some value' end # etc... end 
Sign up to request clarification or add additional context in comments.

4 Comments

They can be initialized only in the method (contructor) initialize()? It's my question.
They can be initialized in any instance method but initialize is the first method called for any given instance so it's the best place to do it.
Why can't it be initialized out of any method? class MyClass @my_var = 'some value' ;end ?
Whenever you create an instance variable it gets associated with whatever the current value of self is, outside of any method if would get associated with the MyClass class object, inside of a method self refers to the current instance of MyClass. So if you initialized outside of the method it would be associated with the class itself rather than a specific instance of that class.
2

Yes, initialize is the right way.

But you may also make:

class MyClass def method1 #I need to do something with @my_var puts @my_var ||= 555 end def method2=(x) #I need to do something with @my_var puts @my_var = x end end #Test: x = MyClass.new x.method1 #555 x.method2= 44 #44 x.method1 #44 

When method1is called the first time, it initialize the variable.

Edit: It does not work as expected, when you assign nil

x = MyClass.new x.method1 #555 x.method2= nil #nil x.method1 #again 555 

This version works better:

class MyClass def method1 @my_var = 555 unless defined? @my_var puts @my_var end def method2=(x) puts @my_var = x end end x = MyClass.new x.method1 #555 x.method2= nil #nil x.method1 #keeps nil 

1 Comment

This is the lazy definition pattern.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.