The bar variable will be available until the class definition is closed. It will not be available inside the methods you define.
You can try running the code in irb:
$ irb irb(main):001:0> class Test irb(main):002:1> bar = 1 irb(main):003:1> puts bar irb(main):004:1> end 1 => nil irb(main):005:0> puts bar NameError: undefined local variable or method `bar' for main:Object from (irb):5 from /usr/bin/irb:11:in `<main>' irb(main):006:0> class Test irb(main):007:1> puts bar irb(main):008:1> end NameError: undefined local variable or method `bar' for Test:Class from (irb):7:in `<class:Test>' from (irb):6 from /usr/bin/irb:11:in `<main>' irb(main):009:0>
Check for instance in methods:
irb(main):018:0> class Test irb(main):019:1> bar = 1 irb(main):020:1> def test irb(main):021:2> puts bar irb(main):022:2> end irb(main):023:1> end => :test irb(main):024:0> a = Test.new => #<Test:0x00000000f447a0> irb(main):025:0> a.test NameError: undefined local variable or method `bar' for #<Test:0x00000000f447a0> from (irb):21:in `test' from (irb):25 from /usr/bin/irb:11:in `<main>'
Check for the presence in the class methods:
irb(main):026:0> class Test irb(main):027:1> bar = 1 irb(main):028:1> def self.test irb(main):029:2> puts bar irb(main):030:2> end irb(main):031:1> end => :test irb(main):032:0> Test.test NameError: undefined local variable or method `bar' for Test:Class from (irb):29:in `test' from (irb):32 from /usr/bin/irb:11:in `<main>'
source share