views:

56

answers:

5

Hi,

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.

+1  A: 

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".

Matthew Flaschen
+1  A: 

Question.classname returns the string "Question". The type of that string is obviously string. Is that what you're asking?

gcores
A: 

Code is wrong. I must not have the classname method in the classrating method.Damn :D. Sorry

Felix
+4  A: 

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.

sepp2k
Thank you very much :)
Felix
A: 

I'm really lost as to what you're trying to accomplish here.

If you just want the name of the class, what's wrong with just object.class.to_s

Question.classrating(Question.classname(q))

returns "String" because your argument is a string. You're calling classname twice, both within the classrating method and in your argument to the classrating method. So you're getting the class name of a Question object, which is "Question", and then you're getting the class name of "Question", which is String.

But I'm still not sure why you're doing this.

Eleo