adding attributes to a Ruby object dynamically

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

    If the name of the attribute is known at code-writing time then you can do what was suggested already:

    class A
    end
    
    a = A.new
    a.age = 20 # Raises undefined method `age='
    
    # Inject attribute accessors into instance of A
    class << a
      attr_accessor :age
    end
    
    a.age = 20 # Succeeds
    a.age # Returns 20
    
    b = A.new
    b.age # Raises undefined method, as expected, since we only modified one instance of A
    

    However, if the attribute's name is dynamic and only known at runtime then you'll have to call attr_accessor a bit differently:

    attr_name = 'foo'
    
    class A
    end
    
    a = A.new
    a.foo = 20 # Raises undefined method `foo='
    
    # Inject attribute accessors into instance of A
    a.instance_eval { class << self; self end }.send(:attr_accessor, attr_name)
    
    a.foo = 20 # Succeeds
    a.foo # Returns 20
    

提交回复
热议问题