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

969 views Asked by At

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?

4

There are 4 answers

2
Francesco Belladonna On BEST ANSWER

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.

2
Cary Swoveland On

Yes, you can!

def owner(iv)
  ObjectSpace.each_object(Class).select { |c| c.instance_variables.include?(iv) }
end

class A
  @a = 1
end

class B
  @b = 2
end

class C
  @a = 3
end

owner :@a #=> [C, A] 
owner :@b #=> [B] 
owner :@c #=> [] 
0
steenslag On

You can put your students as values in a Hash, with their names as key:

class Student
  attr_accessor :name
end

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

students_by_name = {}
students_by_name[student.name] = student
p students_by_name["John Doe"]
# => #<Student:0x00000000baf770 @name="John Doe">

But those student names better be unique - a new John Doe will trample over the old one.

1
joseramonc On

calling class on an instance should give you the class object.

student.class
# => Student