From: Lars Haugseth Date: 2012-09-19T23:11:30+09:00 Subject: Re: Class variables On 09/19/2012 03:03 PM, Jeroen Lodewijks wrote: > Jan E. wrote in post #1076455: > >> class Test { >> >> int var = 5; >> >> void show() { >> System.out.println(var); >> } >> >> } > > Hi all, > > This is exactly the question that I also wanted to ask, being new to > Ruby. I just registered 5 min ago and see almost the first post is the > very same probem. > > What I want to do achieve is: I want a variable known throughout the > scope of the class but that is *not* always the same variable if you > instanciate a new object of the class (I like to achieve what the java > code above does). > > For instance: > > class Test > var = 5 > > def show > puts var > end > > def set(value) > var = value > end > end > > test1 = Test.new > test1.set 10 > > test2 = Test.new > test2.set 20 > > test1.show > test2.show > > Should show 10 and 20 > > How do I do this? class Test attr_accessor :var def initialize @var = 5 end end test1 = Test.new test1.var = 10 test2 = Test.new test2.var = 20 test3 = Test.new puts test1.var # => 10 puts test2.var # => 20 puts test3.var # => 5 The attr_accessor statement creates the var= and var methods for setting and getting the value of the @var instance variable. You can set it to some default value for new instances in the initialize method. -- Lars Haugseth