adding attributes to a Ruby object dynamically

前端 未结 6 2022
梦毁少年i
梦毁少年i 2020-12-24 06:07

I have an object created, and I want, based on some conditional check, to add some attributes to this object. How can I do this? To explain what I want:

A=O         


        
6条回答
  •  暖寄归人
    2020-12-24 07:09

    You can use instance_variable_set to set a variable on an instance of the Object class (and instance_variable_get to get it.) The Object class doesn't have any attributes you can set directly.

    However, I suspect this is not the best solution for what you are trying to achieve; it is not the norm to directly work with the Object class, but rather to define or use classes that inherit from it, that have the attributes you want to work with.

提交回复
热议问题