Reputation: 11542
I am trying to retrieve the class name of an object. When I tried using the const_get, i am getting the entire model's table structure. So I used the following code.
Code
def classname(object)
return object.class.to_s.split("(")[0]
end
def classrating(object_id)
classtype = classname(object_id)
return classtype
end
Script/Console
>> q = Question.new
=> #<Question id: nil, question_info: nil, profile_id: nil, rating: nil, created_at: nil, updated_at: nil>
>> Question.classname(q)
=> "Question"
>> Question.classrating(Question.classname(q))
=> "String"
>> q.class
=> Question(id: integer, question_info: string, profile_id: integer, rating: integer, created_at: datetime, updated_at: datetime)
As you can see, when Question.classname is called, it returns Question and when the same input i called from Question.classrating, it returns String. I am just returning the same output from the Question.classname.
Can you please tell me whether what am I doing wrong, that the value gets changed.
Thanks.
Upvotes: 2
Views: 3396
Reputation: 370102
First of all, you can just use object.class.name
to get an object's class name as a string.
The reason that your second call returns "String" is simply that you call Question.classname(q)
which returns "Question"
and then you call Question.classrating("Question")
which returns "String" because "Question"
is a string.
Upvotes: 8
Reputation: 11542
Code is wrong. I must not have the classname method in the classrating method.Damn :D. Sorry
Upvotes: 0
Reputation: 12656
Question.classname returns the string "Question". The type of that string is obviously string. Is that what you're asking?
Upvotes: 1
Reputation: 284786
First, classrating
is effectively the same as classname
. So you're basically doing:
classname(classname(Question.new))
You're returning the class name of the class name of q
. q
is a Question
, so the class name is "Question"
. "Question"
is a String
, so its class name is "String"
.
Upvotes: 1