Accessing Ruby Class Variables with class_eval and instance_eval

前端 未结 4 1420
[愿得一人]
[愿得一人] 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:18

    Well, probably the best answer is "just because": the instance_eval in a nutshell creates some kind of singleton proc that is invoked with the binding of a given object. I agree that is sounds a bit strange, but it is what it is.

    If you execute instance_eval with a string, you will even get a warning that your method tries to access class variable:

    irb(main):038:0> Test.new.instance_eval "@@a"
    (eval):1: warning: class variable access from toplevel singleton method
    NameError: (eval):1:in `irb_binding': uninitialized class variable ...
    

提交回复
热议问题