get instance variable name from itself in ruby

后端 未结 4 1056
花落未央
花落未央 2021-01-13 11:43

I have an instance variable @foo and I want to write some code so that I get string \'foo\'

any hint?

4条回答
  •  死守一世寂寞
    2021-01-13 11:57

    You can call the method instance_variables to get the name of all instance variables of an object. Caution though that instance variables are only included in that list after they have been initialized.

    >> class A; attr_accessor :foo; end
    => nil
    >> a = A.new
    => #
    >> a.instance_variables
    => []
    >> a.foo = 42
    => 42
    >> a.instance_variables
    => ["@foo"]
    

提交回复
热议问题