Adding an instance variable to a class in Ruby

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

    I wrote a gem for this some time ago. It's called "Flexible" and not available via rubygems, but was available via github until yesterday. I deleted it because it was useless for me.

    You can do

    class Foo
        include Flexible
    end
    f = Foo.new
    f.bar = 1
    

    with it without getting any error. So you can set and get instance variables from an object on the fly. If you are interessted... I could upload the source code to github again. It needs some modification to enable

    f.bar?
    #=> true
    

    as method for asking the object if a instance variable "bar" is defined or not, but anything else is running.

    Kind regards, musicmatze

提交回复
热议问题