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?
each class has an
initialize()method that acts similar to a constructor in other languages, instance variables should be initialized there: