adding attributes to a Ruby object dynamically

前端 未结 6 2025
梦毁少年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:53

    class Person; end
    person = Person.new
    person.age # throws NoMethodError
    
    if true
      person.singleton_class.module_eval { attr_accessor :age }
    end
    
    person.age = 123
    person.age #=> 123
    
    person2 = Person.new
    person2.age #=> throws NoMethodError
    

提交回复
热议问题