adding attributes to a Ruby object dynamically

前端 未结 6 2031
梦毁少年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 06:51

    This adds the attribute to only the object:

    a = Object.new
    if (something happens)
      class << a
        attr_accessor :age
      end
      a.age = new_age_value
    end
    

提交回复
热议问题