From: "Jesús Gabriel y Galán" Date: 2012-09-18T19:32:57+09:00 Subject: Re: Class variables On Tue, Sep 18, 2012 at 12:07 PM, Aleksander Ciesielski wrote: > Is it obligatory to use instance variables in classes? Can't we just write > something like this: > > class Test > var = 5 > > def show > puts var > end > end > > test = Test.new > test.show > p test.var This doesn't work. The keyword def starts a new scope, so the "var" inside "show" is a different local variable than the var in the scope of the class. Even if this weren't the case, this would resemble more a class instance variable than an instance variable, since all instances of the class would have the same value for "var". By the way, you can achieve this using "define_method" instead of "def", since define_method is a closure and can see the surrounding scope: 1.9.2p290 :012 > class Test 1.9.2p290 :013?> var = 5 1.9.2p290 :014?> define_method :show do 1.9.2p290 :015 > puts var 1.9.2p290 :016?> end 1.9.2p290 :017?> end => # 1.9.2p290 :018 > Test.new.show 5 => nil But as I said, all instances see the same value: 1.9.2p290 :019 > a = Test.new => # 1.9.2p290 :020 > b = Test.new => # 1.9.2p290 :021 > a.show 5 => nil 1.9.2p290 :022 > b.show 5 => nil and you cannot change it on a per instance case. That's what instance variables are for. The last part > p test.var can never work, since you don't define a method called var. Jesus.