Access variables programmatically by name in Ruby

后端 未结 11 887
没有蜡笔的小新
没有蜡笔的小新 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:27

    OK, it DOES work in instance methods, too, and, based on your specific requirement (the one you put in the comment), you could do this:

    local_variables.each do |var|
      puts var if (eval(var).class != Fixnum)
    end
    

    Just replace Fixnum with your specific type checking.

提交回复
热议问题