开发者

Retrieving Class Name from an Object in Ruby

开发者_StackOverflow

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.


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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜