Adding an instance variable to a class in Ruby

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

    Ruby provides methods for this, instance_variable_get and instance_variable_set. (docs)

    You can create and assign a new instance variables like this:

    >> foo = Object.new
    => #
    
    >> foo.instance_variable_set(:@bar, "baz")
    => "baz"
    
    >> foo.inspect
    => #
    

提交回复
热议问题