Accessing Ruby Class Variables with class_eval and instance_eval

Viewed 13687

I have the following:

class Test
    @@a = 10

    def show_a()
        puts "a: #{@@a}"
    end

    class << self
      @@b = '40'

      def show_b
        puts "b: #{@@b}"
    end
  end
end

Why does following work:

Test.instance_eval{show_b}
b: 40
=> nil

But I can't access @@b directly?

Test.instance_eval{ @@b }
NameError: uninitialized class variable @@b in Object

Likewise, the following works

t = Test.new
t.instance_eval{show_a}
a: 10
=> nil

but the following fails

t.instance_eval{ @@a }
NameError: uninitialized class variable @@a in Object

I don't understand why I can't access the Class Variables directly from the instance_eval blocks.

4 Answers
Related