Adding an instance variable to a class in Ruby

前端 未结 8 583
太阳男子
太阳男子 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
    => #<Object:0x2aaaaaacc400>
    
    >> foo.instance_variable_set(:@bar, "baz")
    => "baz"
    
    >> foo.inspect
    => #<Object:0x2aaaaaacc400 @bar=\"baz\">
    
    0 讨论(0)
  • 2021-01-31 03:42

    The other solutions will work perfectly too, but here is an example using define_method, if you are hell bent on not using open classes... it will define the "var" variable for the array class... but note that it is EQUIVALENT to using an open class... the benefit is you can do it for an unknown class (so any object's class, rather than opening a specific class)... also define_method will work inside a method, whereas you cannot open a class within a method.

    array = []
    array.class.send(:define_method, :var) { @var }
    array.class.send(:define_method, :var=) { |value| @var = value }
    

    And here is an example of it's use... note that array2, a DIFFERENT array also has the methods, so if this is not what you want, you probably want singleton methods which I explained in another post.

    irb(main):001:0> array = []
    => []
    irb(main):002:0> array.class.send(:define_method, :var) { @var }
    => #<Proc:0x00007f289ccb62b0@(irb):2>
    irb(main):003:0> array.class.send(:define_method, :var=) { |value| @var = value }
    => #<Proc:0x00007f289cc9fa88@(irb):3>
    irb(main):004:0> array.var = 123
    => 123
    irb(main):005:0> array.var
    => 123
    irb(main):006:0> array2 = []
    => []
    irb(main):007:0> array2.var = 321
    => 321
    irb(main):008:0> array2.var
    => 321
    irb(main):009:0> array.var
    => 123
    
    0 讨论(0)
提交回复
热议问题