Adding an instance variable to a class in Ruby

前端 未结 8 603
太阳男子
太阳男子 2021-01-31 02:39

How can I add an instance variable to a defined class at runtime, and later get and set its value from outside of the class?

I\'m looking for a metaprogramming so

8条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 03:39

    Readonly, in response to your edit:

    Edit: It looks like I need to clarify that I'm looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class. A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about. Sorry for the confusion.

    I think you don't quite understand the concept of "open classes", which means you can open up a class at any time. For example:

    class A
      def hello
        print "hello "
      end
    end
    
    class A
      def world
        puts "world!"
      end
    end
    
    a = A.new
    a.hello
    a.world
    

    The above is perfectly valid Ruby code, and the 2 class definitions can be spread across multiple Ruby files. You could use the "define_method" method in the Module object to define a new method on a class instance, but it is equivalent to using open classes.

    "Open classes" in Ruby means you can redefine ANY class at ANY point in time... which means add new methods, redefine existing methods, or whatever you want really. It sounds like the "open class" solution really is what you are looking for...

提交回复
热议问题