Adding an instance variable to a class in Ruby

前端 未结 8 600
太阳男子
太阳男子 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:21

    Mike Stone's answer is already quite comprehensive, but I'd like to add a little detail.

    You can modify your class at any moment, even after some instance have been created, and get the results you desire. You can try it out in your console:

    s1 = 'string 1'
    s2 = 'string 2'
    
    class String
      attr_accessor :my_var
    end
    
    s1.my_var = 'comment #1'
    s2.my_var = 'comment 2'
    
    puts s1.my_var, s2.my_var
    

提交回复
热议问题