Access variables programmatically by name in Ruby

后端 未结 11 938
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 19:15

I\'m not entirely sure if this is possible in Ruby, but hopefully there\'s an easy way to do this. I want to declare a variable and later find out the name of the variable.

11条回答
  •  天命终不由人
    2020-11-27 19:31

    I do not know of any way to get a local variable name. But, you can use the instance_variables method, this will return an array of all the instance variable names in the object.

    Simple call:

    object.instance_variables
    

    or

    self.instance_variables
    

    to get an array of all instance variable names.

提交回复
热议问题