Search code examples
rubyreflectionintrospection

Ruby - How to find class name given an instance variable?


How can I find a class name given its instance variables? For example, given the class below:

class Student
  attr_accessor :name
end

and, the object below:

student = Student.new
student.name = "John Doe"

How can I get the class name (or its Class object) from the instance variable name of the student object?


Solution

  • You can't, you can get the class name of an instance variable, but the "instance variable of an instance" has its own class (it's still an object).

    So student.name.class will return String, student.class will return Student.

    If you want such a binding (student name => student class) you have to write your own system to keep track of it. But in any case, your system can't block anyone from writing "John Doe" anywhere and claim its an instance variable for a Student object.

    No programming language that currently I'm aware of provides a feature as the one you requested.

    Perhaps you want something like student.name = StudentName.new("John Doe")? In this case you can definitely keep track of it, but it's up to you create it and make it works.