Adding an instance variable to a class in Ruby

前端 未结 8 577
太阳男子
太阳男子 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:35

    It looks like all of the previous answers assume that you know what the name of the class that you want to tweak is when you are writing your code. Well, that isn't always true (at least, not for me). I might be iterating over a pile of classes that I want to bestow some variable on (say, to hold some metadata or something). In that case something like this will do the job,

    # example classes that we want to tweak
    class Foo;end
    class Bar;end
    klasses = [Foo, Bar]
    
    # iterating over a collection of klasses
    klasses.each do |klass|
      # #class_eval gets it done
      klass.class_eval do
        attr_accessor :baz
      end
    end
    
    # it works
    f = Foo.new
    f.baz # => nil
    f.baz = 'it works' # => "it works"
    b = Bar.new
    b.baz # => nil
    b.baz = 'it still works' # => "it still works"
    

提交回复
热议问题