Accessing Ruby Class Variables with class_eval and instance_eval

前端 未结 4 1416
[愿得一人]
[愿得一人] 2021-01-31 04:39

I have the following:

class Test
    @@a = 10

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

    class << self
      @@b = \'40\'

      def show_b
         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 05:11

    I just asked the same question to Matz during the RubyKaigi party. I was half-drunk, but he was perfectly sober, so you can take this as the definitive answer.

    Anton is right - the reason why you cannot access class variables through instance_eval() is "just because". Even class_eval() shares the same issue (Matz himself wasn't totally sure about class_eval() until I told him I'd already tried it). More specifically: scope-wise, class variables are more like constants than instance variables, so switching self (as instance_eval() and class_eval() do) is not going to make any difference when it comes to accessing them.

    In general, it might be a good idea to avoid class variables altogether.

提交回复
热议问题